MySQL select 并计算 2 个具有不同 where 子句的列

MySQL select and count 2 colums with different where clauses

我觉得应该很容易,但是根本就不行。我有一个 table,我想生成一个显示分组项目的图表,其中一个 where 子句(第 1 列)应该显示状态为 0 的条目,而另一个 where 子句(第 2 列)应该显示显示状态为 1 的条目。

如果我只执行一个查询,它工作正常,但我想在一个组合查询中同时拥有这两个(状态 0 和状态 1)。

状态 0 查询:

SELECT item,quantity, COUNT(status) FROM `table` 
WHERE `retry` = 1
AND `status` = 0
GROUP BY item,quantity
ORDER BY COUNT(status) DESC

状态 1 查询:

SELECT item,quantity, COUNT(status) FROM `table` 
WHERE `retry` = 1
AND `status` = 1
GROUP BY item,quantity
ORDER BY COUNT(status) DESC

我尝试将两者结合起来(没用)

SELECT t1.item,t1.quantity, COUNT(t2.status), COUNT(t3.status) FROM `table` AS t1
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '0' AND `retry` = 1 GROUP BY item,quantity) AS t2
ON t1.ndc = t2.ndc
LEFT JOIN (SELECT item,status FROM `table` WHERE `status` = '1' AND `retry` = 1 GROUP BY item,quantity) AS t3
ON t1.ndc = t3.ndc
WHERE 1
GROUP BY t1.item,t1.quantity
ORDER BY COUNT(t2.status) DESC

请检查这个,它对你有用吗?

请试试这个

 SELECT
    item,quantity,
    COUNT(case when status =1 then 1 end) AS status1,
    COUNT(case when status =0 then 1 end) AS status0
  FROM table
h=12=hh=14=hh=13=hh 测试日期:h=11=hh w=10=sh