How to pivot two columns in SQL Server?

烈酒焚心 提交于 2020-04-16 05:49:11

问题


I have the following table

 UserName   UserId   
    -----      ----    
    Bob         445       
    Bob         450       
    Rachel      512       
    Rachel      520       
    Rachel      570       
    Simon       771       
    Simon       760 

and I am trying to pivot it so that a new column is created for each username, with UserID's listed per UserName

Bob       Rachel       Simon
445          512        771
450          520        760
             570

回答1:


Just in case you were looking for a dynamic pivot

Example

Declare @SQL varchar(max) = '
Select *
From (
        Select * 
              ,RN = row_number() over (partition by username order by UserId) 
        from #YourTable
     ) A
 Pivot (max(UserID) For [UserName] in (' + stuff((Select distinct ',' + QuoteName([UserName]) From  #YourTable Order By 1 For XML Path('')),1,1,'')  + ') ) p
'

--Print @SQL
Exec(@SQL);

Returns

RN  Bob   Rachel    Simon
1   445   512       760
2   450   520       771
3   NULL  570       NULL



回答2:


This is tricky. You can use aggregation, but you need to number the rows:

select max(case when username = 'Bob' then uid end) as bob,
       max(case when username = 'Rachel' then uid end) as Rachel,
       max(case when username = 'Simon' then uid end) as Simon      
from (select t.*,
             row_number() over (partition by username order by uid) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

Note: This orders the values by uid, which is slightly different from your result set. SQL tables represent unordered sets. There is no ordering of the original rows, unless a column specifies that ordering. If you have such a column, you can use that instead of order by uid for row_number().



来源:https://stackoverflow.com/questions/60800185/how-to-pivot-two-columns-in-sql-server

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