admin

如何在SQL Server中透视两列?

sql

我有下表

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

我试图对其进行透视,以便为每个用户名创建一个新列,并按每个UserName列出UserID

Bob       Rachel       Simon
445          512        771
450          520        760
             570

阅读 479

收藏
2021-07-01

共1个答案

admin

万一您正在寻找动态枢纽

例子

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);

退货

RN  Bob   Rachel    Simon
1   445   512       760
2   450   520       771
3   NULL  570       NULL
2021-07-01