Can anyone write query for this? - sql

My table is as below
recordId fwildcardId refNumber wildcardName wildcardValue comments
404450 154834 2 aaa p p
404450 154833 1 aa oi p
406115 154867 1 98 ff ff
406199 154869 1 aa aaaa ssss
406212 154880 1 bbbbb card comm
and I need the output as
RecordId fwildcardid1 refNo1 Name1 Value1 comments1 fwildcardid2 refNo2 Name2 Value2 comments2 fwildcardid3 refNo3 Name3 Value3 comments3
404450 154834 2 aaa p p 154833 1 aa oi p
406115 Null Null Null Null Null Null Null Null Null Null 154867 1 98 ff ff
406199 Null Null Null Null Null 154869 1 aa aaaa ssss Null Null Null Null
I tried pivoting like below , but didnt succeed .
select t1.recordId,t1.wildcardid as fwildcardId,t1.refNo as refNumber,t2.wildcardName,t1.attributeValue as wildcardValue,t1.comments
into #tempp
from fwildcards t1
inner join fwildcardattributes t2 on t2.WildcardID=t1.attributenameid and t2.MarketID=5
inner join fitems t3 on t3.recordid=t1.recordid and t3.marketid=5
order by recordid,attributenameid
select * from #tempp
pivot (min (wildcardValue) for wildcardName in ([aaa],[aa],[aaaa],[98],[kki],[bbbbb],[SUN])) as wildcardValuePivot

In order to get this result, you will have to UNPIVOT and hen PIVOT the data. The UNPIVOT will take the values in the columns fwildcardId, refNumber, wildcardName, wildcardValue and comments and turns them into rows. Once the data is in rows, then you can apply the PIVOT function to get the final result.
To unpivot the data, you can use either the UNPIVOT function or you can use the CROSS APPLY and VALUES clause.
UNPIVOT:
select recordid,
col+cast(rn as varchar(10)) col,
unpiv_value
from
(
select recordid,
cast(fwildcardid as varchar(10)) fwildcardid,
cast(refnumber as varchar(10)) refnumber,
cast(wildcardname as varchar(10)) name,
cast(wildcardvalue as varchar(10)) value,
cast(comments as varchar(10)) comments,
row_number() over(partition by recordid
order by fwildcardid) rn
from tempp
) d
unpivot
(
unpiv_value
for col in (fwildcardid, refnumber, name, value, comments)
) c
See SQL Fiddle with Demo.
CROSS APPLY and VALUES:
select recordid,
col+cast(rn as varchar(10)) col,
value
from
(
select recordid,
cast(fwildcardid as varchar(10)) fwildcardid,
cast(refnumber as varchar(10)) refnumber,
wildcardname,
wildcardvalue,
comments,
row_number() over(partition by recordid
order by fwildcardid) rn
from tempp
) d
cross apply
(
values
('fwildcardid', fwildcardid),
('refnumber', refnumber),
('name', wildcardname),
('value', wildcardvalue),
('comments', comments)
) c (col, value)
See SQL Fiddle with Demo.
These convert the results in a format:
| RECORDID | COL | VALUE |
------------------------------------
| 404450 | fwildcardid1 | 154833 |
| 404450 | refnumber1 | 1 |
| 404450 | name1 | aa |
| 404450 | value1 | oi |
| 404450 | comments1 | p |
| 404450 | fwildcardid2 | 154834 |
When you unpivot data into the same column, it has to be the same datatype. You will notice that I applied a cast to the columns so the datatype is the same.
Once the data is in the row format, you can convert it back into columns with PIVOT:
select *
from
(
select recordid,
col+cast(rn as varchar(10)) col,
unpiv_value
from
(
select recordid,
cast(fwildcardid as varchar(10)) fwildcardid,
cast(refnumber as varchar(10)) refnumber,
cast(wildcardname as varchar(10)) name,
cast(wildcardvalue as varchar(10)) value,
cast(comments as varchar(10)) comments,
row_number() over(partition by recordid
order by fwildcardid) rn
from tempp
) d
unpivot
(
unpiv_value
for col in (fwildcardid, refnumber, name, value, comments)
) c
) src
pivot
(
max(unpiv_value)
for col in (fwildcardid1, refnumber1, name1, value1, comments1,
fwildcardid2, refnumber2, name2, value2, comments2)
) piv;
See SQL Fiddle with Demo.
The above version works great if you have a known number of columns, but if you will have an unknown number of values that will be converted into columns, then you will need to use dynamic sql to get the result:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(c.col+cast(rn as varchar(10)))
from
(
select row_number() over(partition by recordid
order by fwildcardid) rn
from tempp
) t
cross apply
(
select 'fwildcardid' col, 1 sortorder union all
select 'refNumber', 2 union all
select 'name', 3 union all
select 'value', 4 union all
select 'comments', 5
) c
group by col, rn, sortorder
order by rn, sortorder
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT recordid,' + #cols + ' from
(
select recordid,
col+cast(rn as varchar(10)) col,
unpiv_value
from
(
select recordid,
cast(fwildcardid as varchar(10)) fwildcardid,
cast(refnumber as varchar(10)) refnumber,
cast(wildcardname as varchar(10)) name,
cast(wildcardvalue as varchar(10)) value,
cast(comments as varchar(10)) comments,
row_number() over(partition by recordid
order by fwildcardid) rn
from tempp
) d
unpivot
(
unpiv_value
for col in (fwildcardid, refnumber, name, value, comments)
) c
) src
pivot
(
max(unpiv_value)
for col in (' + #cols + ')
) p '
execute(#query);
See SQL Fiddle with Demo. Both of these give the result:
| RECORDID | FWILDCARDID1 | REFNUMBER1 | NAME1 | VALUE1 | COMMENTS1 | FWILDCARDID2 | REFNUMBER2 | NAME2 | VALUE2 | COMMENTS2 |
-------------------------------------------------------------------------------------------------------------------------------
| 404450 | 154833 | 1 | aa | oi | p | 154834 | 2 | aaa | p | p |
| 406115 | 154867 | 1 | 98 | ff | ff | (null) | (null) | (null) | (null) | (null) |
| 406199 | 154869 | 1 | kki | aaaa | ssss | (null) | (null) | (null) | (null) | (null) |
| 406212 | 154880 | 1 | bbbbb | card | comm | (null) | (null) | (null) | (null) | (null) |

No Pivot No Cross Apply
According to edited Question.
select
DISTINCT
A.recordId AS recordId,
A1.fwildcardId AS fwildcardId1,
A1.refNumber AS refNumber1,
A1.wildcardName AS wildcardName1,
A1.wildcardValue AS wildcardValue1,
A1.comments AS comments1,
A2.fwildcardId AS fwildcardId2,
A2.refNumber AS refNumber2,
A2.wildcardName AS wildcardName2,
A2.wildcardValue AS wildcardValue2,
A2.comments AS comments2,
A3.fwildcardId AS fwildcardId3,
A3.refNumber AS refNumber3,
A3.wildcardName AS wildcardName3,
A3.wildcardValue AS wildcardValue3,
A3.comments AS comments3,
A4.fwildcardId AS fwildcardId4,
A4.refNumber AS refNumber4,
A4.wildcardName AS wildcardName4,
A4.wildcardValue AS wildcardValue4,
A4.comments AS comments4,
A5.fwildcardId AS fwildcardId5,
A5.refNumber AS refNumber5,
A5.wildcardName AS wildcardName5,
A5.wildcardValue AS wildcardValue5,
A5.comments AS comments5,
A6.fwildcardId AS fwildcardId6,
A6.refNumber AS refNumber6,
A6.wildcardName AS wildcardName6,
A6.wildcardValue AS wildcardValue6,
A6.comments AS comments6,
A7.fwildcardId AS fwildcardId7,
A7.refNumber AS refNumber7,
A7.wildcardName AS wildcardName7,
A7.wildcardValue AS wildcardValue7,
A7.comments AS comments7,
A8.fwildcardId AS fwildcardId8,
A8.refNumber AS refNumber8,
A8.wildcardName AS wildcardName8,
A8.wildcardValue AS wildcardValue8,
A8.comments AS comments8,
A9.fwildcardId AS fwildcardId9,
A9.refNumber AS refNumber9,
A9.wildcardName AS wildcardName9,
A9.wildcardValue AS wildcardValue9,
A9.comments AS comments9,
A10.fwildcardId AS fwildcardId10,
A10.refNumber AS refNumber10,
A10.wildcardName AS wildcardName10,
A10.wildcardValue AS wildcardValue10,
A10.comments AS comments10
from Table_name A
LEFt JOIN Table_name A1 ON A.recordId=A1.recordId AND A1.wildcardName='aaa'
LEFT JOIN Table_name A2 ON A.recordId=A2.recordId AND A2.wildcardName='aa'
LEFT JOIN Table_name A3 ON A.recordId=A3.recordId AND A3.wildcardName='98'
LEFT JOIN Table_name A4 ON A.recordId=A4.recordId AND A4.wildcardName=''
LEFT JOIN Table_name A5 ON A.recordId=A5.recordId AND A5.wildcardName=''
LEFT JOIN Table_name A6 ON A.recordId=A6.recordId AND A6.wildcardName=''
LEFT JOIN Table_name A7 ON A.recordId=A7.recordId AND A7.wildcardName=''
LEFT JOIN Table_name A8 ON A.recordId=A8.recordId AND A8.wildcardName=''
LEFT JOIN Table_name A9 ON A.recordId=A9.recordId AND A9.wildcardName=''
LEFT JOIN Table_name A10 ON A.recordId=A10.recordId AND A10.wildcardName=''
SQL Fiddle

Related

How to find duplicate row when any one word of desc column matching within group

I have a result like this:
I need to update "flag" column as duplicate when any one word from the row matches with second row within group of "mfgid" column.
--test dataset
declare #table as table
(id int,
mfgid int,
[desc] varchar(100))
insert into #table
values (1,111,'abc xyz pqr'),
(2,111,'abc tyu fgh'),
(3,222,'abc pqr'),
(4,222,'lmn stu'),
(5,333,'pqr spd hki abc'),
(6,333,'lmn jsk pqr klo')
How can I do this?
Here is a possible solution
WITH K AS
(
SELECT mfgid,
value,
count(*) over ( partition by mfgid, value order by mfgid) Dups
FROM #Table cross apply STRING_SPLIT([desc], ' ')
)
SELECT T.*,
IIF(
EXISTS(SELECT 1 FROM K WHERE K.mfgid = T.mfgid AND K.Dups > 1),
'Duplicte',
''
) Flag
FROM #Table T;
Results:
+----+-------+-----------------+----------+
| id | mfgid | desc | Flag |
+----+-------+-----------------+----------+
| 1 | 111 | abc xyz pqr | Duplicte |
| 2 | 111 | abc tyu fgh | Duplicte |
| 3 | 222 | abc pqr | |
| 4 | 222 | lmn stu | |
| 5 | 333 | pqr spd hki abc | Duplicte |
| 6 | 333 | lmn jsk pqr klo | Duplicte |
+----+-------+-----------------+----------+
Demo
two possible solutions below:
--test dataset
declare #table as table
(id int,
mfgid int,
[desc] varchar(100))
insert into #table
values (1,111,'abc xyz pqr'),
(2,111,'abc tyu fgh'),
(3,222,'abc pqr'),
(4,222,'lmn stu'),
(5,333,'pqr spd hki abc'),
(6,333,'lmn jsk pqr klo')
Solution 1:
If you have only 4 words in string (based on your screenshot)
;with cte2 as
(select *
from (select id,
mfgid,
parsename(replace(s.[desc],' ','.'),1) as [a1],
parsename(replace(s.[desc],' ','.'),2) as [a2],
parsename(replace(s.[desc],' ','.'),3) as [a3],
parsename(replace(s.[desc],' ','.'),4) as [a4]
from #table as s) as a
unpivot (testval FOR val IN (a1, a2, a3, a4)) unpvt
)
select m.id, m.mfgid, m.[desc], t.flag
from #table as m
outer apply
(select top (1) 'duplicate' as flag
from cte2 as a
join cte2 as b
on a.mfgid = b.mfgid
and a.id != b.id
and a.testval = b.testval
and m.mfgid = a.mfgid) as t
test is here
Solution 2:
If you have more that 4 words in string
;with cte as
( select t.*, s.[value]
from #table as t
cross apply
(select ltrim(rtrim(split.a.value('.','varchar(100)'))) as [value]
from (select cast('<M>'+replace([desc],' ','</M><M>')+'</M>' as xml) as data) as a
cross apply data.nodes ('/M') as split(a)
) as s
)
select m.id, m.mfgid, m.[desc], t.flag
from #table as m
outer apply
(select top (1) 'duplicate' as flag
from cte as a
join cte as b
on a.mfgid = b.mfgid
and a.id != b.id
and a.Value = b.Value
and m.mfgid = a.mfgid) as t
test is here
This assumes the OP is using SQL Server 2016+, as they haven't let us know the version:
WITH Split AS(
SELECT T.id,
T.mfgid,
T.[desc],
SS.[value]
FROM #table T
CROSS APPLY STRING_SPLIT([desc],' ') SS)
SELECT S.id,
S.mfgid,
S.[desc],
CASE MAX(Dups) WHEN 0 THEN NULL ELSE 'Duplicate' END AS Flag
FROM Split S
CROSS APPLY (SELECT COUNT(*) AS [Dups]
FROM Split ca
WHERE ca.mfgid = S.mfgid
AND ca.[value] = S.[value]
AND ca.id != S.id) C
GROUP BY S.id,
S.mfgid,
S.[desc];

SQL Query - Row to columns not really a pivot

I'm trying to move certain fields of an ID into columns, but it doesn't appear to match all the pivot examples I am finding. All the examples I can find use some form of a grouping on a field value. I want to use more of a placement regardless of the value in the field. I want to do this in a query without looping via code. Data source example (sorry couldn't figure out how to format a table on the post so I used a code snippet):
+----+--------+--------+
| ID | Field1 | Field2 |
+----+--------+--------+
| 1 | NULL | NULL |
| 2 | Jim | 321 |
| 2 | Jack | 54 |
| 2 | Sue | 985 |
| 2 | Gary | 654 |
| 3 | Herb | 332 |
| 3 | Chevy | 10 |
+----+--------+--------+
Result set I'm trying to generate:
+----+------+------+-------+------+------+------+
| ID | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 |
+----+------+------+-------+------+------+------+
| 1 | NULL | NULL | | | | |
| 2 | Jim | 321 | Jack | 54 | Sue | 985 |
| 3 | Herb | 332 | Chevy | 10 | | |
+----+------+------+-------+------+------+------+
SQL Fiddle: http://sqlfiddle.com/#!3/a225a/1
;with cte as (
select id
, field1
, field2
, ROW_NUMBER() over (partition by id order by field1, field2) r
from #t
)
select c1.id
, c1.field1 col1
, c1.field2 col2
, c2.field1 col3
, c2.field2 col4
, c3.field1 col5
, c3.field2 col6
from cte c1
left outer join cte c2 on c2.id = c1.id and c2.r = c1.r + 1
left outer join cte c3 on c3.id = c1.id and c3.r = c1.r + 2
where (c1.r % 3) = 1
Explanation
ROW_NUMBER() over (partition by id order by field1, field2) r. This line ensures that we have a column counting up from 1 for each id. This allows us to distinguish between the multiple rows.
The CTE is used to save typing the same statement for c1, c2 and c3.
The joins ensure that all items in a row have the same id, and that data for col1, col3 and col5 (likewise for col2, col4 and col6) is taken from consecutive rows. We're using left outer joins because there may not rows in the source table for these columns.
The where statement says to take the first row of each set of 3 for the data in c1 (with c2 and c3 thus being the second and third of each set, thanks to the earlier join).
Here's a solution using dynamic sql that works though I'm sure there's a better way to do it. Caution, it's a bit painful. First it builds the list of columns to pivot and select, builds the dynamic sql and runs it.
DECLARE #PivotColumns as varchar(max), #SelectColumns as varchar(max), #sql as varchar(max)
SELECT #PivotColumns = ISNULL(#PivotColumns + ',', '') + ColNum,
#SelectColumns = ISNULL(#SelectColumns + ',', '') + 'NULLIF(' + ColNum + ', ''NULL'') as ' + ColNum
from (select distinct 'Col' + cast(ROW_NUMBER() OVER (partition by id order by id) as varchar) as ColNum
from (select id,
isnull(field1,'NULL') as field1,
isnull(field2,'NULL') as field2
from weirdpivot) cols
unpivot
(
value
for col in (field1, field2)
) unpivoted) DistinctColumns
set #sql = '
select id, + ' + #SelectColumns + '
from (select
''Col'' + cast(ROW_NUMBER() OVER (partition by id order by id) as varchar) as colnum
,id
,value
from (select id,
isnull(field1,''NULL'') as field1,
isnull(field2,''NULL'') as field2
from weirdpivot) cols
unpivot
(
value
for col in (field1, field2)
) u) unpivoted
pivot
(
max(value)
for colnum in (' + #PivotColumns + ')
) p'
exec (#sql)

SQL Pivoting or Transposing or ... column to row?

I have a question and this looks way better in SQLfiddle:
http://www.sqlfiddle.com/#!3/dffa1/2
I have a table with multirows for each user with datestamp and test results and i would like to transpose or pivot it into one line result as follows where each user has listed all time and value results:
USERID PSA1_time PSA1_result PSA2_time PSA2_result PSA3_time PSA3_result ...
1 1999-.... 2 1998... 4 1999... 6
3 1992... 4 1994 6
4 2006 ... 8
Table below:
CREATE TABLE yourtable
([userid] int, [Ranking] int,[test] varchar(3), [Date] datetime, [result] int)
;
INSERT INTO yourtable
([userid], [Ranking],[test], [Date], [result])
VALUES
('1', '1', 'PSA', 1997-05-20, 2),
('1', '2','PSA', 1998-05-07, 4),
('1', '3','PSA', 1999-06-08, 6),
('1', '4','PSA', 2001-06-08, 8),
('1', '5','PSA', 2004-06-08, 0),
('3', '1','PSA', 1992-05-07, 4),
('3', '2','PSA', 1994-06-08, 6),
('4', '1','PSA', 2006-06-08, 8)
;
Since you want to PIVOT two columns my suggestion would be to unpivot the date and result columns first, then apply the PIVOT function.
The unpivot process will convert the two columns date and result into multiple rows:
select userid,
col = test +'_'+cast(ranking as varchar(10))+'_'+ col,
value
from yourtable t1
cross apply
(
select 'time', convert(varchar(10), date, 120) union all
select 'result', cast(result as varchar(10))
) c (col, value)
See Demo. This will give you a result:
| USERID | COL | VALUE |
--------------------------------------
| 1 | PSA_1_time | 1997-05-20 |
| 1 | PSA_1_result | 2 |
| 1 | PSA_2_time | 1998-05-07 |
| 1 | PSA_2_result | 4 |
| 1 | PSA_3_time | 1999-06-08 |
Now that you have the data in this format, then you can apply pivot to get the max/min value for each item in col:
If you have a limited number of columns, then you can hard-code the query:
select *
from
(
select userid,
col = test +'_'+cast(ranking as varchar(10))+'_'+ col,
value
from yourtable t1
cross apply
(
select 'time', convert(varchar(10), date, 120) union all
select 'result', cast(result as varchar(10))
) c (col, value)
) d
pivot
(
max(value)
for col in (PSA_1_time, PSA_1_result,
PSA_2_time, PSA_2_result,
PSA_3_time, PSA_3_result,
PSA_4_time, PSA_4_result,
PSA_5_time, PSA_5_result)
) piv;
See SQL Fiddle with Demo
If you have unknown columns, then you will need to use dynamic SQL:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(test +'_'+cast(ranking as varchar(10))+'_'+ col)
from yourtable
cross apply
(
select 'time', 1 union all
select 'result', 2
) c (col, so)
group by test, ranking, col, so
order by Ranking, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT userid,' + #cols + '
from
(
select userid,
col = test +''_''+cast(ranking as varchar(10))+''_''+ col,
value
from yourtable t1
cross apply
(
select ''time'', convert(varchar(10), date, 120) union all
select ''result'', cast(result as varchar(10))
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p '
execute sp_executesql #query;
See SQL Fiddle with Demo. Both versions will give a result:
| USERID | PSA_1_TIME | PSA_1_RESULT | PSA_2_TIME | PSA_2_RESULT | PSA_3_TIME | PSA_3_RESULT | PSA_4_TIME | PSA_4_RESULT | PSA_5_TIME | PSA_5_RESULT |
------------------------------------------------------------------------------------------------------------------------------------------------------
| 1 | 1997-05-20 | 2 | 1998-05-07 | 4 | 1999-06-08 | 6 | 2001-06-08 | 8 | 2004-06-08 | 0 |
| 3 | 1992-05-07 | 4 | 1994-06-08 | 6 | (null) | (null) | (null) | (null) | (null) | (null) |
| 4 | 2006-06-08 | 8 | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |

How to transform records data into columns

Please find the sample data:
h_company_id company_nm mainphone1 phone_cnt
20816 800 Flowers 5162377000 3
20816 800 Flowers 5162377131 1
20820 1st Source Corp. 5742353000 3
20821 1st United Bancorp 5613633400 2
20824 3D Systems Inc. 8033273900 4
20824 3D Systems Inc. 8033464010 1
11043 3I Group PLC 2079757115 1
11043 3I Group PLC 2079753731 15
Desired Output:
h_company_id company_nm mainphone1 phone_cnt mainphone2 phone_cnt2
20816 800 Flowers 5162377000 3 5162377131 1
20820 1st Source Corp. 5742353000 3 NULL NULL
20821 1st United Bancorp 5613633400 2 NULL NULL
20824 3D Systems Inc. 8033273900 4 8033464010 1
11043 3I Group PLC 2079757115 1 2079753731 15
(copy above in notepad/excel)
Hi Guys,
I want to transpose records of columns mainphone1 and phone_cnt as new columns namely mainphone2, phone_cnt2 so that the data in column h_company_id should be unique means there should be only single entry of h_company_id.
Thanks in advance!
Transforming from rows into columns is called a PIVOT and there are several different ways that this can be done in SQL Server.
Aggregate / CASE: You can use an aggregate function along with a CASE expression. This will work by applying the row_number() windowing function to the data in your table:
select h_company_id, company_nm,
max(case when seq = 1 then mainphone1 end) mainphone1,
max(case when seq = 1 then phone_cnt end) phone_cnt1,
max(case when seq = 2 then mainphone1 end) mainphone2,
max(case when seq = 2 then phone_cnt end) phone_cnt2
from
(
select h_company_id, company_nm, mainphone1, phone_cnt,
row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
) d
group by h_company_id, company_nm;
See SQL Fiddle with Demo. The CASE expression checks if the sequence number has the value 1 or 2 and then places the data in the column.
UNPIVOT / PIVOT: Since you want to PIVOT data that exists in two columns, then you will want to UNPIVOT the mainphone1 and phone_cnt columns first to get them in the same column, then apply the PIVOT function.
The UNPIVOT code will be similar to the following:
select h_company_id, company_nm,
col+cast(seq as varchar(10)) col,
value
from
(
select h_company_id, company_nm,
cast(mainphone1 as varchar(15)) mainphone,
cast(phone_cnt as varchar(15)) phone_cnt,
row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
) d
unpivot
(
value
for col in (mainphone, phone_cnt)
) unpiv;
See Demo. This query gets the data in the following format:
| H_COMPANY_ID | COMPANY_NM | COL | VALUE |
---------------------------------------------------------------
| 11043 | 3I Group PLC | mainphone1 | 2079753731 |
| 11043 | 3I Group PLC | phone_cnt1 | 15 |
| 11043 | 3I Group PLC | mainphone2 | 2079757115 |
| 11043 | 3I Group PLC | phone_cnt2 | 1 |
| 20816 | 800 Flowers | mainphone1 | 5162377000 |
Then you apply the PIVOT function to the values in col:
select h_company_id, company_nm,
mainphone1, phone_cnt1, mainphone2, phone_cnt2
from
(
select h_company_id, company_nm,
col+cast(seq as varchar(10)) col,
value
from
(
select h_company_id, company_nm,
cast(mainphone1 as varchar(15)) mainphone,
cast(phone_cnt as varchar(15)) phone_cnt,
row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
) d
unpivot
(
value
for col in (mainphone, phone_cnt)
) unpiv
) src
pivot
(
max(value)
for col in (mainphone1, phone_cnt1, mainphone2, phone_cnt2)
) piv;
See SQL Fiddle with Demo.
Multiple Joins: You can also join on your table multiple times to get the result.
;with cte as
(
select h_company_id, company_nm, mainphone1, phone_cnt,
row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
)
select c1.h_company_id,
c1.company_nm,
c1.mainphone1,
c1.phone_cnt phone_cnt1,
c2.mainphone1 mainphone2,
c2.phone_cnt phone_cnt2
from cte c1
left join cte c2
on c1.h_company_id = c2.h_company_id
and c2.seq = 2
where c1.seq = 1;
See SQL Fiddle with Demo.
Dynamic SQL: Finally if you have an unknown number of values that you want to transform, then you will need to implement dynamic SQL to get the result:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(col+cast(seq as varchar(10)))
from
(
select row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
) d
cross apply
(
select 'mainphone', 1 union all
select 'phone_cnt', 2
) c (col, so)
group by seq, so, col
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT h_company_id, company_nm,' + #cols + '
from
(
select h_company_id, company_nm,
col+cast(seq as varchar(10)) col,
value
from
(
select h_company_id, company_nm,
cast(mainphone1 as varchar(15)) mainphone,
cast(phone_cnt as varchar(15)) phone_cnt,
row_number() over(partition by h_company_id order by mainphone1) seq
from yourtable
) d
unpivot
(
value
for col in (mainphone, phone_cnt)
) unpiv
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo. All give a result:
| H_COMPANY_ID | COMPANY_NM | MAINPHONE1 | PHONE_CNT1 | MAINPHONE2 | PHONE_CNT2 |
-----------------------------------------------------------------------------------------
| 20820 | 1st Source Corp. | 5742353000 | 3 | (null) | (null) |
| 20821 | 1st United Bancorp | 5613633400 | 2 | (null) | (null) |
| 20824 | 3D Systems Inc. | 8033273900 | 4 | 8033464010 | 1 |
| 11043 | 3I Group PLC | 2079753731 | 15 | 2079757115 | 1 |
| 20816 | 800 Flowers | 5162377000 | 3 | 5162377131 | 1 |
The following could work (assuming your table is called company):
SELECT
c1.h_company_id,
c1.company_nm,
c1.mainphone1,
c1.phone_cnt,
c2.mainphone1 AS mainphone2,
c2.phone_cnt AS phone_cnt2
FROM
company AS c1
LEFT JOIN
company AS c2 ON c2.h_company_id = c1.h_company_id
However, to respect good practice, wouldn't it be better to separate your data in two tables?
the company table, with 2 columns: h_company_id(PK) and company_nm
the phone table, with 4 columns: phone_id (PK), h_company_id (FK), mainphone and phone_cnt
It would allow you to have as many phone numbers per company as you want (including none).
Try this query. This will help you
SELECT t.H_COMPANY_ID,t.COMPANY_NM, a.mainphone1,a.PHONE_CNT,b.mainphone1 mainphone2,b.PHONE_CNT PHONE_CNT2 FROM table_name t
INNER JOIN
(
SELECT h_company_id,phone_cnt,mainphone1 FROM table_name
WHERE mainphone1
IN(
SELECT max(mainphone1) mainphone1 FROM table_name GROUP BY h_company_id
)
)a ON t.H_COMPANY_ID = a.h_company_id
INNER JOIN
(
SELECT h_company_id,phone_cnt,mainphone1 FROM table_name
WHERE mainphone1
IN(
SELECT min(mainphone1) mainphone1 from table_name GROUP BY h_company_id
)
)b ON t.H_COMPANY_ID = b.H_COMPANY_ID
GROUP BY t.H_COMPANY_ID,a.mainphone1,t.COMPANY_NM,a.PHONE_CNT,b.mainphone1,b.PHONE_CNT

How do I Pivot Vertical Data to Horizontal Data SQL with Variable Row Lengths?

Okay I have the following table.
Name ID Website
Aaron | 2305 | CoolSave1
Aaron | 8464 | DiscoWorld1
Adriana | 2956 | NewCin1
Adriana | 5991 | NewCin2
Adriana | 4563 NewCin3
I would like to transform it into the following way.
Adriana | 2956 | NewCin1 | 5991 | NewCin2 | 4563 | NewCin3
Aaron | 2305 | CoolSave1 | 8464 | DiscoWorld | NULL | NULL
As you can see i am trying to take the first name from the first table and make a single row with all the IDs / Websites associated with that name. The problem is, there is a variable amount of websites that may be associated with each name. To handle this i'd like to just make a table with with the number of fields sequal to the max line item, and then for the subsequent lineitems, plug in a NULL where there are not enough data.
In order to get the result, you will need to apply both the UNPIVOT and the PIVOT functions to the data. The UNPIVOT will take the columns (ID, website) and convert them to rows, once this is done, then you can PIVOT the data back into columns.
The UNPIVOT code will be similar to the following:
select name,
col+'_'+cast(col_num as varchar(10)) col,
value
from
(
select name,
cast(id as varchar(11)) id,
website,
row_number() over(partition by name order by id) col_num
from yt
) src
unpivot
(
value
for col in (id, website)
) unpiv;
See SQL Fiddle with Demo. This gives a result:
| NAME | COL | VALUE |
-------------------------------------
| Aaron | id_1 | 2305 |
| Aaron | website_1 | CoolSave1 |
| Aaron | id_2 | 8464 |
| Aaron | website_2 | DiscoWorld1 |
As you can see I applied a row_number() to the data prior to the unpivot, the row number is used to generate the new column names. The columns in the UNPIVOT must also be of the same datatype, I applied a cast to the id column in the subquery to convert the data to a varchar prior to the pivot.
The col values are then used in the PIVOT. Once the data has been unpivoted, you apply the PIVOT function:
select *
from
(
select name,
col+'_'+cast(col_num as varchar(10)) col,
value
from
(
select name,
cast(id as varchar(11)) id,
website,
row_number() over(partition by name order by id) col_num
from yt
) src
unpivot
(
value
for col in (id, website)
) unpiv
) d
pivot
(
max(value)
for col in (id_1, website_1, id_2, website_2, id_3, website_3)
) piv;
See SQL Fiddle with Demo.
The above version works great if you have a limited or known number of values. But if the number of rows is unknown, then you will need to use dynamic SQL to generate the result:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME( col+'_'+cast(col_num as varchar(10)))
from
(
select row_number() over(partition by name order by id) col_num
from yt
) t
cross apply
(
select 'id' col union all
select 'website'
) c
group by col, col_num
order by col_num, col
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT name,' + #cols + '
from
(
select name,
col+''_''+cast(col_num as varchar(10)) col,
value
from
(
select name,
cast(id as varchar(11)) id,
website,
row_number() over(partition by name order by id) col_num
from yt
) src
unpivot
(
value
for col in (id, website)
) unpiv
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p '
execute(#query);
See SQL Fiddle with Demo. Both versions give the result:
| NAME | ID_1 | WEBSITE_1 | ID_2 | WEBSITE_2 | ID_3 | WEBSITE_3 |
------------------------------------------------------------------------
| Aaron | 2305 | CoolSave1 | 8464 | DiscoWorld1 | (null) | (null) |
| Adriana | 2956 | NewCin1 | 4563 | NewCin3 | 5991 | NewCin2 |