带有COUNTS的SQL GROUP BY - 当计数为0时如何始终返回一行

时间:2010-12-07 13:25:04

标签: sql-server tsql count group-by

继我的previous question之后,我现在有了以下SQL:

SELECT CONVERT(VARCHAR(10), Date, 120) AS Date, 
       COUNT(*)                        AS Total, 
       COUNT(CASE 
               WHEN ErrorCode = -2 THEN 1 
             END)                      AS TimeOutErrors, 
       COUNT(CASE 
               WHEN ErrorCode IS NOT NULL THEN 1 
             END)                      AS TotalErrors 
FROM   Table 
WHERE  Type = 7 
       AND Date = CONVERT(VARCHAR(10), Dateadd(d, -1, Getdate()), 120) 
GROUP  BY Date

返回昨天类型7的所有记录,计数为-2错误和总错误数。

但是,如果昨天没有类型7的记录

,则返回0行

在这种情况下是否可以让它返回所有0?

即:

Date       Total TimeOutErrors TotalErrors
---------- ----- ------------- -----------
2010-12-06 0     0             0

bcp正在解析此查询,以使用SQL代理

每天保存到日志文件

1 个答案:

答案 0 :(得分:3)

您需要OUTER JOIN

...
FROM   
(SELECT CONVERT(VARCHAR(10), Dateadd(d, -1, Getdate()), 120) AS [Date]) D
LEFT OUTER JOIN Table T
ON  D.[Date] = T.[Date]  AND T.Type = 7
GROUP BY D.[Date]