如何获取重复的行并在SQL中添加为列?

时间:2016-09-19 19:34:30

标签: sql

我在这里阅读了许多不同的问题而且我没有找到这个问题,尽管它看起来像人们有时会做的事情。 我所拥有的是一张如下表:

Person_id   Person_Phone_Number
a           11545623
b           21323545
c           45654655
d           54455896
e           21458437
f           14564680
a           32545542
c           98745682
e           10589621
g           23568954
a           56468756

我需要的是输出:

Person_id   Person_Phone_Number    New_Column_1    New_Column_2
a           11545623               32545542        56468756
b           21323545
c           45654655               98745682
d           54455896
e           21458437               10589621
f           14564680
g           23568954

1 个答案:

答案 0 :(得分:0)

IF SQL Server

;with cteBase as (
      Select *,RowNr = Row_Number() over (Partition By Person_id Order By Person_Phone_Number)
       From  @YourTable
)
Select Person_ID
      ,Person_Phone_Number = max(case when RowNr=1 then Person_Phone_Number else '' end)     
      ,New_Column_1        = max(case when RowNr=2 then Person_Phone_Number else '' end)       
      ,New_Column_2        = max(case when RowNr=3 then Person_Phone_Number else '' end)       
 From  cteBase
 Group By Person_ID
 Order By 1

返回

Person_ID   Person_Phone_Number    New_Column_1    New_Column_2
a           11545623               32545542        56468756
b           21323545        
c           45654655               98745682 
d           54455896        
e           10589621               21458437 
f           14564680        
g           23568954