由于您想要 PIVOT 两列数据,因此您可以执行此操作的一种方法是同时应用 UNPIVOT 和 PIVOT 函数。UNPIVOT 会将多列category
和value
多行转换,然后您可以应用 PIVOT 来获得最终结果:
select record,
category1, value1,
category2, value2,
category3, value3
from
(
select record, col+cast(seq as varchar(10)) col, val
from
(
select record, category,
cast(value as nvarchar(50)) value,
row_number() over(partition by record order by category) seq
from tablevar
) d
unpivot
(
val
for col in (category, value)
) unpiv
) src
pivot
(
max(val)
for col in (category1, value1, category2, value2, category3, value3)
) piv;
请参阅SQL Fiddle with Demo。
如果您有未知数量的值,那么您将不得不使用类似于此的动态 SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(col+cast(seq as varchar(10)))
from
(
select row_number() over(partition by record order by category) seq
from tablevar
) d
cross apply
(
select 'category', 1 union all
select 'value', 2
) c (col, so)
group by seq, so, col
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT record,' + @cols + '
from
(
select record, col+cast(seq as varchar(10)) col, val
from
(
select record, category,
cast(value as nvarchar(50)) value,
row_number() over(partition by record order by category) seq
from tablevar
) d
unpivot
(
val
for col in (category, value)
) unpiv
) x
pivot
(
max(val)
for col in (' + @cols + ')
) p '
execute(@query);
请参阅带有演示的 SQL Fiddle