如何针对不同的GROUP BY为多个COUNT编写SQL查询?

时间:2011-04-01 15:18:23

标签: mysql sql

我的一位同事正在研究SQL查询。在几次加入(工作人员到任务的帐户)后,她有一些类似的信息:

Worker       Account    Date        Task_completed
Bob Smith    12345      01/01/2010  Received
Bob Smith    12345      01/01/2010  Received
Bob Smith    12345      01/01/2010  Processed
Sue Jones    23456      01/01/2010  Received
...

最终她想要的是这样的 - 对于每个帐户,每个帐户,每个帐户为该帐户完成了多少个任务?

Worker       Account    Date        Received_count  Processed_count
Bob Smith    12345      01/01/2010  2               1

......还有其他几种可以统计的状态。

获得一个这些计数非常简单:

SELECT
  COUNT(Task_completed)
FROM 
  (the subselect)
WHERE 
  Task_completed = 'Received'
GROUP BY
  worker, account, date

但我不确定最好的办法。 基本上我们希望多个COUNT使用不同的GROUP BY s 。我能想到的最好的事情是多次复制和粘贴子查询,将WHERE更改为“已处理”等,然后将所有这些加在一起,只选择每个子计数。

有更明显的方法吗?

1 个答案:

答案 0 :(得分:5)

SELECT  worker, account, date,
        SUM(task_completed = 'Received') AS received_count,
        SUM(task_completed = 'Processed') AS processed_count
FROM    mytable
GROUP BY
        worker, account, date