我有一个SELECT语句,它从几个产生这个的JOINS中收集数据:
Site Description Status
1 Project 1 Not Started
1 Project 5 In Progress
1 Project 2 Testing
1 Project 12 Complete
1 Project 2 Not Started
2 Project 13 Not Started
2 Project 20 Testing
2 Project 21 In Progress
2 Project 22 In Progress
2 Project 23 Testing
3 Project 24 Not Started
3 Project 25 Not Started
3 Project 26 Testing
3 Project 29 Complete
我想总结一下每个网站的状态:
Site Not Started In Progress Testing Complete
1 2 1 1 1
2 1 2 2 0
3 2 0 1 1
我应该可以使用" WITH"用于处理输出的子句。目前,它看起来像这样:
WITH SiteData AS (SELECT data from multiple JOINS...)
SELECT Site, Description, Status FROM SiteData
因此,我不想只显示数据列,而是希望将其转换为各种各种状态的项目计数。
这有意义吗?
答案 0 :(得分:4)
此类数据转换称为 pivot 。有几种方法可以将行数据转换为列。
您可以将聚合函数与CASE
:
select site,
sum(case when Status = 'Not Started' then 1 else 0 end) [Not Started],
sum(case when Status = 'In Progress' then 1 else 0 end) [In Progress],
sum(case when Status = 'Testing' then 1 else 0 end) Testing,
sum(case when Status = 'Complete' then 1 else 0 end) Complete
from sitedata
group by site
您将使用现有查询替换sitedata
。
或者您可以使用PIVOT
功能:
select site,
[Not Started],
[In Progress],
Testing,
Complete
from
(
select [Site], Status
from sitedata
) src
pivot
(
count(Status)
for Status in ([Not Started], [In Progress], Testing, Complete)
) piv
如果您有Status
个未知数值,则可以使用动态SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME([Status])
from SiteData
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT site, ' + @cols + ' from
(
select [Site], Status
from sitedata
) x
pivot
(
count(Status)
for Status in (' + @cols + ')
) p '
execute(@query)
每个查询的结果都是相同的:
| SITE | NOT STARTED | IN PROGRESS | TESTING | COMPLETE |
---------------------------------------------------------
| 1 | 2 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 | 0 |
| 3 | 2 | 0 | 1 | 1 |
编辑#1,如果你想要一个Total
行,那么你可以使用:
select
case when site is not null then cast(site as varchar(10)) else 'Total' end Site,
sum([Not Started]) [Not Started],
Sum([In Progress])[In Progress],
Sum(Testing) Testing,
sum(Complete) Complete,
Sum([Not Started]+[In Progress]+ Testing+ Complete) Total
from
(
select [Site], Status
from sitedata
) src
pivot
(
count(Status)
for Status in ([Not Started], [In Progress], Testing, Complete)
) piv
group by rollup (site)