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

Mysql返回所有部门的所有状态计数,如果为空,则返回0,mysql,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 当前结果 +------+--------+--

你好

我在生成一个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 |
+------+--------+-------+
以下是SQLFIDLE链接:

您可以尝试以下方法:

演示:


我永远无法理解被一行代码重写的SQL代码。。。此外,我们需要示例数据(放在上面),我们可以使用..反向工程一个带有一些结果集的一行SQL,如果没有示例数据,使用SQL代码几乎是不可能的。对不起,我将编辑我的帖子。感谢您,但请查看您想要的结果以及在线线性SQL中的某些部分。。我认为您需要使用
LEFT JOIN
。您只需要第一个子查询。连接没有意义。你有状态表吗hi@KKK我认为它没有解决我的问题它输出的结果与我以前的查询相同。如果你运行代码,第一个查询将返回dept和status的所有组合,然后与其他子查询连接以获得计数。是的,我运行了。对不起,伙计,我试图在sqlfiddle上运行它,但结果仍然是sameI已经更新了答案,也在sqlfiddle上,chck out。
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