Nathan Long
Nathan Long

Reputation: 125892

How can I write a SQL query with multiple COUNTs for different GROUP BYs?

One of my coworkers is working on a SQL query. After several joins (workers to accounts to tasks), she's got some information sort of like this:

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
...

Ultimately what she wants is something like this - for each date, for each account, how many tasks did each worker complete for that account?

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

... and there are several other statuses to count.

Getting one of these counts is pretty easy:

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

But I'm not sure the best way to get them all. Essentially we want multiple COUNTs using different GROUP BYs. The best thing I can figure out is to copy and paste the subquery several times, change the WHERE to "Processed", etc, and join all those together, selecting just the count from each one.

Is there a more obvious way to do this?

Upvotes: 2

Views: 548

Answers (1)

Quassnoi
Quassnoi

Reputation: 425261

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

Upvotes: 5

Related Questions