Reputation: 516
I have this statement:
SELECT COUNT(AccedentId) AS NumberOfAccedentInYear
FROM Accident
GROUP BY DriverId, YEAR(AccedentDate)
HAVING (DriverId =@DriverId)<3
When there are rows, I get a valid count, but when there are no rows, the result is empty. I'd like the result to be 0 when there are no matching rows.
Upvotes: 0
Views: 2781
Reputation: 280252
Maybe you wanted this (I'm keeping obvious syntax and spelling errors that I can't really correct without more information):
SELECT NumberOfAccedentInYear = ISNULL
(
(SELECT COUNT(AccedentId)
FROM Accident
GROUP BY DriverId, YEAR(AccedentDate)
HAVING (DriverId =@DriverId)<3))
, 0
);
For anyone curious about the COALESCE vs ISNULL discussion, and why I changed my answer to use ISNULL, @kanav rightly pointed out that COALESCE is more expensive. COALESCE evaluates the subquery twice, as I explained here: https://stackoverflow.com/a/10669660/61305
Upvotes: 5