Reputation: 3181
I need this query to return 0 when there are no status='Completed' for those EmpID who doesn't have any Completed status
select EmployeeID, count(Status)
from tbl1
group by EmployeeID
where Status = 'Completed';
How can I do that?
Upvotes: 0
Views: 38
Reputation: 35333
The issue is if an employee doesn't have a completed status they get excluded from the results. You need to get a count that includes them so
.
SELECT A.EmployeeID, coalesce(B.Count,0)
FROM (SELECT Distinct EmployeeID FROM tbl1) A
LEFT JOIN (SELECT EmployeeID, count(Status)
FROM tbl1
WHERE status = 'Completed'
GROUP BY Employee ID)
on A.EmployeeID = B.EmployeeID
Alternatively: don't eliminate them
SELECT EmployeeID, sum(case when status = 'completed' then 1 else 0 end)
FROM tbl1
GROUP BY EmployeeID
pro's cons either way depending on indexes and data volumes.
Upvotes: 1