For ease of discussion, consider this basic table (Test) in Access...
ID division name role
1 1 Frank 100
2 2 David 101
3 3 John 101
4 2 Mike 102
5 2 Rob 102
7 3 Dave 102
8 3 Greg 102
I want to count the users of a certain role in a division. If I do a simple count(), I get the proper 0 returned:
SELECT COUNT(ID) as ct
FROM Test
WHERE role >=101 and division=1;
yields
division ct
1 0
However, I want to include the division number in the results (for the sake of further joining, reports, etc) and it always returns null/no rows instead of the division and count of 0:
SELECT division, COUNT(ID) as ct
FROM Test WHERE role >=101
GROUP BY division
HAVING division=1;
or
SELECT division, COUNT(ID) as ct
FROM Test
WHERE role >=101 AND division=1
GROUP BY division;
yields
division ct
I originally came about this because I would also like this to work if the user enters a division that is not in the table (like 4)...
SELECT division, COUNT(ID) as ct
FROM Test
WHERE role >=101 AND division IN (1,2,4)
GROUP BY division;
yields
division ct
2 3
instead of
division ct
1 0
2 3
4 0
Is it not possible to return division along with the count if the count is 0?
How about this:
SELECT division, ISNULL(ct,0) AS ct
FROM divisionTable
LEFT JOIN
(SELECT division, COUNT(ID) as ct FROM Test WHERE role >=101 GROUP BY division) CountQuery
ON divisionTable.division = CountQuery.division
WHERE divisionTable.division IN (1,2,4)
This works in SQL server, so maybe...
SELECT division, COUNT(ID) AS ct
FROM Test
WHERE role >= 101
GROUP BY ALL division
HAVING division = 1 ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With