您将需要PIVOT
对此使用动态 sql,您的代码将与此类似:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(dept)
from yourtablewithDepartments
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT *
from
(
<your query goes here>
) src
pivot
(
max(incidentcount)
for dept in (' + @cols + ')
) piv '
execute(@query)
如果您发布更多详细信息,例如表结构等,则可以对其进行细化以满足您的需求。
编辑,根据您当前的查询,您似乎可以使用以下内容:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsNull AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(department)
from myincidentdb
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Details, ' + @cols + '
from
(
select Details, Department
from myincidentdb
) x
pivot
(
count(Department)
for Department in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle