我有这个MS SQL 2005查询:
SELECT
DATEDIFF(dd, getdate(), CreatedOn) as Day,
COUNT(CreatedOn) as 'Active Cases'
FROM
[dbo].[IncidentBase]
WHERE
(StatusCode != 6 AND StatusCode != 5)
AND (CaseTypeCode = '200000' OR CaseTypeCode = '200005' OR CaseTypeCode = '200006')
GROUP BY
DATEDIFF(dd, getdate(), CreatedOn)
ORDER BY
Day DESC
并返回这样的内容:
-1 10
-2 6
-5 4
-7 8
我真的希望它像:
-1 10
-2 6
-3 0
-4 0
-5 4
-6 0
-7 8
(在没有记录的日期之间插入零)
我该怎么做?
非常感谢提前!
答案 0 :(得分:2)
在子查询上尝试返回所有日期的外连接
SELECT table_cal.day_diff as "Day",
COALESCE(table_count.base_count,0) as "Active Cases"
FROM
(SELECT DISTINCT DATEDIFF(dd, getdate(), ibase.CreatedOn) as day_diff
FROM [dbo].[IncidentBase] ibase) table_cal
LEFT OUTER JOIN
(SELECT DATEDIFF(dd, getdate(), ibase.CreatedOn) as day_diff,
COUNT(ibase.CreatedOn) as base_count
FROM [dbo].[IncidentBase] ibase
WHERE ibase.StatusCode NOT IN (5,6) AND ibase.CaseTypeCode IN ('200000','200005','200006')
GROUP BY DATEDIFF(dd, getdate(), ibase.CreatedOn)) table_count
ON (table_cal.day_diff = table_count.day_diff)
ORDER BY table_cal.day_diff DESC
背后的想法非常简单。您需要一个子查询来生成现有日期列表,另一个子查询生成结果值。然后你将两者连接起来并将空值替换为0。