Question: Say you had the following tables:
| Group | |
| id | name |
|---|---|
| Item | ||
| id | group_id | status |
|---|---|---|
How do you generate frequency counts grouped by status, in such a way that the frequency counts are columns of a row with the group_id, given three status codes (0 == ok, 1 == fail, 2 == pending)? That is, how do you get to the following table:
| Frequencies | |||
| group_id | ok_count | fail_count | pending_count |
|---|---|---|---|
The following SQL should do the trick:
SELECT g.Group, ok_count, fail_count, pending_count FROM Group g LEFT JOIN ( SELECT group_id, COUNT(status) as ok_count FROM Item WHERE status = 0 GROUP BY status, group_id ) ok ON g.group_id = ok.group_id LEFT JOIN ( SELECT group_id, COUNT(status) as fail_count
FROM Item WHERE status = 1 GROUP BY status, group_id ) fail ON g.group_id = fail.group_id LEFT JOIN ( SELECT group_id, COUNT(status) as pending_count FROM Item WHERE status = 2 GROUP BY status, group_id ) pending ON g.group_id = pending.group_id
Previously: No Subject