如何在SQL Server中透视两列?
我有下表
UserName UserId ----- ----
Bob 445
Bob 450
Rachel 512
Rachel 520
Rachel 570
Simon 771
Simon 760
我试图对其进行透视,以便为每个用户名创建一个新列,并按每个UserName列出UserID
Bob Rachel Simon445 512 771
450 520 760
570
回答:
万一您正在寻找动态枢纽
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 Simon1 445 512 760
2 450 520 771
3 NULL 570 NULL
以上是 如何在SQL Server中透视两列? 的全部内容, 来源链接: utcz.com/qa/410589.html