如果没有找到记录则返回0

时间:2014-08-07 02:06:15

标签: sql ms-access

我正在尝试计算每月MS Access数据库中的记录数。到目前为止,我有这个查询,它工作正常;

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

返回结果

--------------------------------------------
|totalproblems| department | dname | month |
--------------------------------------------
|10           |1           |bob    |1      |
|3            |2           |sam    |1      |
|8            |3           |mary   |1      |
--------------------------------------------

这是预期的。我需要的是还要返回没有任何问题记录的部门

--------------------------------------------
|totalproblems| department | dname | month |
--------------------------------------------
|10           |1           |bob    |1      |
|3            |2           |sam    |1      |
|8            |3           |mary   |1      |
|0            |4           |sue    |1      |
--------------------------------------------

我尝试了NZ(COUNT(*),0) AS totalproblems,它创建了另一个列,其值与totalproblems相同,减去任何0的

我已尝试IIF(ISNULL(totalproblems),0)返回空列

我试过SELECT IFNULL(COUNT(*) AS totalproblems,0) 这给了我一个Syntax error (missing operator) in query expression

不确定还有什么可以尝试,或者我做错了什么我做错了。

2 个答案:

答案 0 :(得分:2)

您需要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;

答案 1 :(得分:0)

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