Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL count() with group by not returning 0/zero records

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?

like image 577
BikeMrown Avatar asked Jan 22 '23 20:01

BikeMrown


2 Answers

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)
like image 160
flayto Avatar answered Jan 31 '23 08:01

flayto


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 ;
like image 21
Damir Sudarevic Avatar answered Jan 31 '23 07:01

Damir Sudarevic