I'm using MS SQL 2008 and I have a table of statuses (id, name) and a table of items (id, name, statusid, deleted).
I want to count the number of items with each status, and have the following query:
SELECT status.id,
ISNULL(COUNT (items.name), 0) AS 'count'
FROM status
LEFT OUTER JOIN items
ON items.statusid = status.id
GROUP BY status.id
The complication is that I want to get all the statuses, with a 0 if there are no items for the status.
The above works fine for this, but when I add in WHERE items.deleted = 0
, it no longer displays the rows with a 0 in them.
Why is the WHERE
clause killing my query? I suspect my method may be wrong...
Thanks :)