3

I have the following query which is not working for my requirement. I need the count zero also returned in the results. I am looking for DocIDs with count zero for the condition specified but those DocIDs are not even showing up in the result.

SELECT DocID, Count(*) AS ArchivedCount FROM Doc WHERE Status <> 'Archived' GROUP BY DocID ORDER BY DocID 
2
  • 3
    So you want to count DocIDs that aren't in the table "Doc"? It's possible to do that. But if those DocIDs aren't in "Doc", what table are they in? Commented Mar 21, 2015 at 22:06
  • Are you sure that DocID is really zero? It might be NULL. In that case you need to use COUNT(COALESCE(DocID, 0)) Commented Mar 21, 2015 at 22:09

1 Answer 1

7

Since you need to use all DocIDs, you should use SUM in place of COUNT, and move the condition into a CASE statement inside the SUM, like this:

SELECT DocID , SUM(CASE WHEN Status <> 'Archived' THEN 1 ELSE 0 END) AS ArchivedCount FROM Doc GROUP BY DocID ORDER BY DocID 

Now the result is going to contain all DocIDs, even the ones with the Status different from 'Archived'.

Sign up to request clarification or add additional context in comments.

2 Comments

Can;t get it, because... Sum of zeros gives... zero!
@MaciejLos But that's what OP is looking for - DocIDs with the count of zero.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.