SQL GROUP BY with COUNTS - how to always return a row when counts are 0
Following on from my previous question, I now have the following 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 NO开发者_如何转开发T NULL THEN 1
END) AS TotalErrors
FROM Table
WHERE Type = 7
AND Date = CONVERT(VARCHAR(10), Dateadd(d, -1, Getdate()), 120)
GROUP BY Date
which returns all records of type 7 for yesterday with a count of -2 errors and a count of total errors.
However, this returns 0 rows if there are no records of type 7 for yesterday
Is it possible to get it to return all 0s when this is the case?
i.e.:
Date Total TimeOutErrors TotalErrors
---------- ----- ------------- -----------
2010-12-06 0 0 0
This query is being parsed by bcp to save to a log file daily using SQL Agent
You need an 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]
精彩评论