MySQL带回多个总计

时间:2015-11-12 15:13:40

标签: php mysql sql

我有简单的MySQL查询:

SELECT who, status, 
COUNT(status) AS Total, completion_status AS Role
FROM `trespondent_360` 
GROUP BY who, status 
ORDER BY who, status

这正确地回溯到数据库中每个人的总数。然后我需要计算他们的completion_status =开始或完成的总计。

输出应该是这样的:

Who          Total          Status          Completed
Mike Smith   1              Self            1
Mike Smith   5              Other           2
Bob Jones    1              Self            0
Bob Jones    6              Other           5

每当我添加上面的代码时,我都会收到操作数应包含1列的错误。见下文

SELECT who, status, 
COUNT(status) AS Total, completion_status AS Role,
(SELECT who, status, COUNT(status) FROM `trespondent_360` 
  WHERE completion_status IN ('Started','Complete')) AS Completed
FROM `trespondent_360` 
GROUP BY who, status 
ORDER BY who, status

我将非常感激地收到有关我需要做的任何建议和反馈。

1 个答案:

答案 0 :(得分:1)

如果您想要计算状态CompleteStarted,可以使用CASE WHEN

SELECT who, status, 
       completion_status AS Role,
       COUNT(status) AS Total,
       COUNT(CASE WHEN status IN ('Started','Complete') THEN 1 END) AS Completed
FROM `trespondent_360` 
GROUP BY who, status 
ORDER BY who, status;

顺便说一下,你应该在completion_status列上使用聚合函数,我知道它适用于MySQL,但它不符合ANSI标准。的 More info why you should do it