拥有包含此值的表格:
name | executing | failed |
-------------------------------
task1 0 1
task2 1 0
task3 1 0
task4 0 0
使用我想要的查询:
executing
任务的总量(示例中为2,task2
和task3
)failed
任务的总量(示例中为1,task1
)executing=0
和failed=0
,示例中的1,task4
)我可以通过以下查询获得前两个:
SELECT IFNULL(SUM(executing), 0) Executing, IFNULL(SUM(failed), 0) Failed FROM mytable;
如何扩展我的查询以便我可以使用待处理任务的总和获得另一列?
提前致谢
预期产出:
executing | failed | pending
----------------------------
2 1 1
答案 0 :(得分:4)
您没有指定结果的方式。我会这样做:
select (case when executing = 1 and failed = 0 then 'Executing'
when failed = 1 then 'Failed'
when executing = 0 and failed = 0 then 'Pending'
else 'Unknown'
end) as status, count(*) as cnt
from t
group by status;
您还可以使用条件聚合轻松转动数据:
select sum(executing = 1 and failed = 0) as Executing,
sum(failed = 1) as Failed,
sum(executing = 0 and failed = 0) as Pending
from t;
这使用MySQL速记将布尔表达式视为数字 - “1”表示true,“0”表示false。
答案 1 :(得分:2)
SELECT SUM(executing) AS Executing
, SUM(failed) as Failed
, SUM(CASE
WHEN executing = 0 AND failed = 0 THEN 1
ELSE 0 END
) AS Pending
FROM mytable;