Hi I would like to write one SQL statement that returns both the count and count(distinct) from the same table but with different WHERE clause.
e.g.
People
-----------------------
ID Name Sex
1 Alex F
2 Alex M
3 Alex M
4 Andy F
5 Andy M
6 Ann F
7 Ann F
In this example, I can write SELECT (SELECT COUNT(1) FROM People), (SELECT COUNT(DISTINCT Name) FROM People), but thats just too many SELECT. So I write SELECT COUNT(1), COUNT(DISTINCT Name) FROM People instead.
But what if I would like to return something like SELECT (SELECT COUNT(1) FROM People), (SELECT COUNT(DISTINCT Name) FROM People WHERE Sex='M'). How do you do the same like above to have less SELECT?
I don’t know if this is related, I know that I can write something like SELECT COUNT(1), SUM(CASE WHEN Sex='M' THEN 1 ELSE 0 END) FROM People to have different WHERE clauses in one SELECT, but thats only for COUNT, it doesn’t handle DISTINCT. How do you use this when DISTINCT is needed?
The DB is SQL Server 2008 R2, Thank you
Try this:
You can see it in SQL fiddle here: