由于 each 有多个值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) |