2

我有这个 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

(在没有记录的日期之间插入零)

我怎样才能做到这一点?

提前谢谢了!

4

1 回答 1

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 替换空值。

于 2013-03-14T07:51:38.030 回答