有几种方法可以获得所需的结果。如果您想要 PIVOT 到列中的值数量有限,那么您可以通过几种不同的方式对查询进行硬编码。
使用 CASE 聚合函数:
select
person,
max(case when seq = 1 then category end) Cat1,
max(case when seq = 1 then activity end) Cat1_Act,
max(case when seq = 2 then category end) Cat2,
max(case when seq = 2 then activity end) Cat2_Act,
max(case when seq = 3 then category end) Cat3,
max(case when seq = 3 then activity end) Cat3_Act
from
(
select person, category, activity,
row_number() over(partition by person
order by category) seq
from yourtable
) d
group by person;
请参阅SQL Fiddle with Demo。通过为每个用户的每个类别分配一个序列或 row_number,您可以使用此行号将行转换为列。
静态枢轴:
如果要应用 PIVOT 函数,那么我首先建议将category
andactivity
列取消透视到多行,然后应用 pivot 函数。
;with cte as
(
select person, category, activity,
row_number() over(partition by person
order by category) seq
from yourtable
)
select person,
cat1, cat1_act,
cat2, cat2_act,
cat3, cat3_act
from
(
select t.person,
col = case
when c.col = 'cat' then col+cast(seq as varchar(10))
else 'cat'+cast(seq as varchar(10))+'_'+col
end,
value
from cte t
cross apply
(
select 'cat', category union all
select 'act', activity
) c (col, value)
) d
pivot
(
max(value)
for col in (cat1, cat1_act, cat2, cat2_act,
cat3, cat3_act)
) piv;
请参阅带有演示的 SQL Fiddle
动态 PIVOT:最后,如果您有未知数量的值,那么您可以使用动态 SQL 来获取结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ','
+ QUOTENAME(case
when d.col = 'cat' then col+cast(seq as varchar(10))
else 'cat'+cast(seq as varchar(10))+'_'+col end)
from
(
select row_number() over(partition by person
order by category) seq
from yourtable
) t
cross apply
(
select 'cat', 1 union all
select 'act', 2
) d (col, so)
group by col, so, seq
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT person, ' + @cols + '
from
(
select t.person,
col = case
when c.col = ''cat'' then col+cast(seq as varchar(10))
else ''cat''+cast(seq as varchar(10))+''_''+col
end,
value
from
(
select person, category, activity,
row_number() over(partition by person
order by category) seq
from yourtable
) t
cross apply
(
select ''cat'', category union all
select ''act'', activity
) c (col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute sp_executesql @query;
请参阅SQL Fiddle with Demo。所有版本都会给出一个结果:
| PERSON | CAT1 | CAT1_ACT | CAT2 | CAT2_ACT | CAT3 | CAT3_ACT |
| Username1 | X | X1 | Y | Y1 | Z | Z1 |