Reputation:
I'm trying to count the number of records in a MS Access database per month. so far I have this query and it works fine;
SELECT COUNT(*) AS totalproblems,
problems.department,
departments.dname,
month(start_date) AS month
FROM problems
INNER JOIN departments on problems.department = departments.department_id
WHERE year(start_date) = '2014'
GROUP BY month(start_date), problems.department, departments.dname
This returns results like so
--------------------------------------------
|totalproblems| department | dname | month |
--------------------------------------------
|10 |1 |bob |1 |
|3 |2 |sam |1 |
|8 |3 |mary |1 |
--------------------------------------------
Which is as expected. What I need though is to also return the departments that didn't have any problems recorded like so
--------------------------------------------
|totalproblems| department | dname | month |
--------------------------------------------
|10 |1 |bob |1 |
|3 |2 |sam |1 |
|8 |3 |mary |1 |
|0 |4 |sue |1 |
--------------------------------------------
I have tried NZ(COUNT(*),0) AS totalproblems
which just created another column with the exact same values as totalproblems minus any 0's
I've tried IIF(ISNULL(totalproblems),0)
which returned an empty column
And I've tried SELECT IFNULL(COUNT(*) AS totalproblems,0)
Which gives me a Syntax error (missing operator) in query expression
Not sure what else to try or what I'm doing wrong with what I've tried.
Upvotes: 1
Views: 924
Reputation: 1269973
You need an outer join
:
SELECT COUNT(problems.department) AS totalproblems, problems.department, departments.dname,
month(problems.start_date) AS month
FROM departments LEFT JOIN
problems
on problems.department = departments.department_id
WHERE (year(problems.start_date) = '2014' OR problems.start_date IS NULL)
GROUP BY month(start_date), problems.department, departments.dname;
Upvotes: 1
Reputation: 1062
SELECT COUNT(*) AS totalproblems,
departments.department_id,
departments.dname,
month(start_date) AS month
FROM departments
LEFT JOIN problems on problems.department = departments.department_id
WHERE year(start_date) = '2014'
GROUP BY month(start_date), department_id.department, departments.dname
Upvotes: 0