Mysql返回所有部门的所有状态的计数如果为null则返回0

时间:2018-05-27 13:12:18

标签: mysql

美好的一天,

我无法生成一个mysql查询,其中我想列出所有状态并返回所有部门的响应数量。这是我尝试过的:

SELECT Status,Dept,Sum(Case when Status !="" Then 1 else 0 end) as Count
FROM result 
GROUP BY  Status,Dept
ORDER BY Status desc

但它只返回该部门下现有记录的状态。如果部门没有包含状态下的任何记录,我希望得到一个返回0的结果。

当前结果

+------+--------+-------+
| Dept | Status | Count |
+------+--------+-------+
| a    | Neg    |     2 |
| b    | Neg    |     3 |
| c    | Neg    |     6 |
| a    | Pos    |     1 |
| b    | Pos    |     2 |
+------+--------+-------+

期望的结果:

+------+--------+-------+
| Dept | Status | Count |
+------+--------+-------+
| a    | Neg    |     2 |
| b    | Neg    |     3 |
| c    | Neg    |     6 |
| a    | Pos    |     1 |
| b    | Pos    |     2 |
| c    | POS    |     0 |
+------+--------+-------+

这是sqlfiddle链接:

http://www.sqlfiddle.com/#!9/a24835/3

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

DEMO:http://www.sqlfiddle.com/#!9/a24835/54

select a.dept,a.status,
       case when b.cnt is null then 0
        else b.cnt end count
from
(select dept,status from
(select dept from result group by dept) i cross join
(select status from result group by status) j) a left join 
(select dept,status,count(1) cnt 
  from result group by dept,status) b
on a.status = b.status and a.dept=b.dept