row convert to column in sql 2008

2019-09-06 16:58发布

问题:

I want to convert a series of rows into a series of columns

create table #cusphone(cusid int,cusph1 int)
insert into #cusphone values(1,48509)
insert into #cusphone values(1,48508)
insert into #cusphone values(1,48507)
insert into #cusphone values(2,48100)

so that the output is like this

            1 48509 48508 48507
            2 48100  null  null   

回答1:

You can use the same approach of rank() and then use the new PIVOT function as follows:

with    cusCte as(
select  cusid,cusph1,RANK() over (partition by cusid order by cusph1) r
from    #cusphone)

SELECT cusid, [1] AS C1, [2] AS C2, [3] AS C3
FROM 
(SELECT cusid,cusph1,r
FROM cusCte) p
PIVOT
(
MIN (cusph1)
FOR r IN
( [1], [2], [3] )
) AS pvt;


回答2:

You did not specify the rules by which something should appear in the first column vs the second column so I guessed that this is based on the occurrence (and thus sorting) of the cusph1 value.

With RankedItems As
    (
    Select cusid, cusph1
        , ROW_NUMBER() OVER( PARTITION BY cusid ORDER BY cusph1 DESC) As Num
    From #cusphone
    )
Select cusid
    , Min(Case When Num = 1 Then cusph1 End) As Col1
    , Min(Case When Num = 2 Then cusph1 End) As Col2
    , Min(Case When Num = 3 Then cusph1 End) As Col3
From RankedItems
Group By cusid