我必须在SQL Server 2012中运行查询,以根据请求状态从表中选择数据。
我正在使用查询而不包括获取当前数据周的where条件。
没有where条件的查询
select * from (SELECT ReqStatus,[priority]
FROM WEEKDATA
group by ReqStatus,[priority] ,Raisedon
)p
pivot (
Count([priority])
For [priority] IN(Critical,High,Medium,Low)
)
as pvt
结果
|ReqStatus | Critical| High| Medium| Low
|----------|---------|-----|-------|----
| Approved | 1 | 0 | 0 | 0
| Assigned | 2 | 0 | 0 | 0
| Closed | 2 | 1 | 1 | 1
| Rejected | 0 | 1 | 0 | 0
当我在当前周数据的查询中包含where条件时
使用Where条件查询
select * from (SELECT ReqStatus,[priority]
FROM WEEKDATA
where DATENAME(wk,Raisedon)=DATENAME(wk,GETUTCDATE())
group by ReqStatus,[priority] ,Raisedon
)p
pivot (
Count([priority])
For [priority] IN(Critical,High,Medium,Low)
)
as pvt
实际结果
|ReqStatus | Critical| High| Medium| Low
|----------|---------|-----|-------|----
| Assigned | 1 | 0 | 0 | 0
| Closed | 0 | 0 | 1 | 0
我得到了上述结果,因为在本周我只有两个状态"分配","关闭"在我的桌子上。但我还需要其他请求状态,例如"已批准","拒绝"在列表中,列中包含0值,即“严重”,“高”,“中”,“低”。
For Instance,
预期结果
|ReqStatus | Critical| High| Medium| Low
|----------|---------|-----|-------|----
| Approved | 0 | 0 | 0 | 0
| Assigned | 1 | 0 | 0 | 0
| Closed | 0 | 0 | 1 | 0
| Rejected | 0 | 0 | 0 | 0
答案 0 :(得分:2)
您可以将CTE与UNION ALL一起使用,以添加值为0的状态。
;WITH CTE_wd AS
(
SELECT ReqStatus,[priority]
FROM WEEKDATA
where DATENAME(wk,Raisedon)=DATENAME(wk,GETUTCDATE())
group by ReqStatus,[priority] ,Raisedon
)
select * from (SELECT ReqStatus,[priority]
FROM CTE_wd
UNION ALL
SELECT DISTINCT w.ReqStatus , '' AS [priority]
FROM WEEKDATA AS w
LEFT JOIN CTE_wd AS wd ON wd.ReqStatus = w.ReqStatus
WHERE wd.ReqStatus IS NULL
)p
pivot (
Count([priority])
For [priority] IN(Critical,High,Medium,Low)
)
as pvt