有几种方法可以将数据转换为列。
您可以将聚合函数与CASE
表达式一起使用:
select name,
max(case when rn = 1 then department end) Department1,
max(case when rn = 2 then department end) Department2,
max(case when rn = 3 then department end) Department3
from
(
select name,
department,
row_number() over(partition by name order by department) rn
from yt
) src
group by name;
请参阅带有演示的 SQL Fiddle
您可以使用 PIVOT 将数据从行转换为列。
select *
from
(
select name,
department,
'Department'
+cast(row_number() over(partition by name order by department) as varchar(10)) col
from yt
) src
pivot
(
max(department)
for col in ([Department1], [Department2], [Department3])
) piv;
请参阅带有演示的 SQL Fiddle
我建议使用动态 SQL 来获得结果,因为每个名称可能有未知数量的部门。动态 SQL 代码将是:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(col)
from
(
select 'department'+
cast(row_number() over(partition by name order by department) as varchar(10)) col
from yt
) src
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name, ' + @cols + '
from
(
select name, department,
''department''+
cast(row_number() over(partition by name order by department) as varchar(10)) col
from yt
) x
pivot
(
max(department)
for col in (' + @cols + ')
) p '
execute(@query);
请参阅带有演示的 SQL Fiddle