由于您使用的是 SQL Server,因此您可以使用PIVOT函数将数据行转换为列。
如果您有已知数量的值,则可以对查询进行硬编码:
select category,
coalesce(project1, 0) project1,
coalesce(project2, 0) project2,
coalesce(project3, 0) project3,
coalesce(project4, 0) project4
from
(
select category, project, amount
from yt
) d
pivot
(
sum(amount)
for project in (project1, project2, project3, project4)
) piv;
请参阅SQL Fiddle with Demo。
但是在您的情况下,听起来您将拥有未知数量的值,因此您将不得不实施动态 SQL 解决方案:
DECLARE @cols AS NVARCHAR(MAX),
@colsNull AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(PROJECT)
from yt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsNull = STUFF((SELECT distinct ', Coalesce(' + QUOTENAME(PROJECT) +', 0) as '+ QUOTENAME(PROJECT)
from yt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT category,' + @colsNull + '
from
(
select category, project, amount
from yt
) d
pivot
(
sum(amount)
for project in (' + @cols + ')
) p '
execute(@query);
请参阅SQL Fiddle with Demo。两者都会给出结果:
| CATEGORY | PROJECT1 | PROJECT2 | PROJECT3 | PROJECT4 |
-------------------------------------------------------------
| Miscellaneous | 1200 | 4500 | 0 | 2300 |
| Travel | 0 | 0 | 3000 | 1000 |