答案 0 :(得分:1)
此 可以通过重复列名来完成,但是,我无法想象为什么会想要这样。
@Col是我们应用别名os.system(MachUp.out)
示例
...[#] as [Tier Value]...
返回
Declare @Col varchar(max) = Stuff((Select Distinct ',' + concat(QuoteName(row_number() over (Partition By ContractID Order by TierDesc)),' as [Tier Value]') From Yourtable Order by 1 For XML Path('')),1,1,'')
Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(row_number() over (Partition By ContractID Order by TierDesc)) From Yourtable Order by 1 For XML Path('')),1,1,'')
Select @SQL = '
Select ContractID,'+@Col+'
From (
Select ContractID
,TierDesc
,ColNr = row_number() over (Partition By ContractID Order by TierDesc)
From YourTable
) Src
Pivot (max(TierDesc) for ColNr in ('+@SQL+') ) pvt
'
Exec(@SQL)
编辑-然后生成的SQL看起来像这样
ContractID Tier Value Tier Value Tier Value
123 tier1 tier2 NULL
555 tier4 tier5 tier6
652 tier0 tier4 NULL
编辑2
Select ContractID
,[1] as [Tier Value]
,[2] as [Tier Value]
,[3] as [Tier Value]
From (
Select ContractID
,TierDesc
,ColNr = row_number() over (Partition By ContractID Order by TierDesc)
From YourTable
) Src
Pivot (max(TierDesc) for ColNr in ([1],[2],[3]) ) pvt