row convert to column in sql 2008

杀马特。学长 韩版系。学妹 提交于 2020-01-06 07:12:13

问题


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


来源:https://stackoverflow.com/questions/2824475/row-convert-to-column-in-sql-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!