由於每個case
都有多個值,因此您需要使用row_number()
來獲取每個類別的單獨列。
在您編寫動態SQL版本之前,我會先寫一個硬編碼版本。代碼將類似於:
SELECT [case], cat1, cat2, cat3
FROM
(
SELECT [case], category,
'cat'+
cast(row_number() over(partition by [case]
order by category) as varchar(10)) seq
FROM yourTable
) x
PIVOT
(
max(category)
for seq in (cat1, cat2, cat3)
)p;
請參閱SQL Fiddle with Demo。
現在你有邏輯下去,那麼你可以將其轉換爲動態SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('cat'+cast(seq as varchar(10)))
from
(
select row_number() over(partition by [case]
order by category) seq
from yourtable
) d
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [case],' + @cols + '
from
(
SELECT [case], category,
''cat''+
cast(row_number() over(partition by [case]
order by category) as varchar(10)) seq
FROM yourTable
) x
pivot
(
max(category)
for seq in (' + @cols + ')
) p '
execute sp_executesql @query;
見SQL Fiddle with Demo。這會給你結果:
| CASE | CAT1 | CAT2 | CAT3 |
|------|------|--------|--------|
| 1 | abc | xx | xyx |
| 2 | asdf | ghj | (null) |
| 3 | dfgh | (null) | (null) |
對不起,格式化失敗 – riverdog