我有许多地方的人处于逐步过程中的各个步骤。我希望能够按位置报告每个步骤的人数,然后报告所有地点的总数。所以我的数据看起来像这样(步骤表)
| ID | STEP_NUM | LOCATION ID |
-------------------------------
| 1 | 1 | 10 |
| 2 | 1 | 12 |
| 3 | 2 | 4 |
| 4 | 1 | 5 |
| 5 | 1 | 6 |
| 6 | 1 | 3 |
| 7 | 3 | 3 |
这个 stackoverflow question and answer(s) Postgresql Multiple counts for a table非常有用,我按位置得到了摘要。这是我当前的查询:
SELECT locations.name,
sum(case when step_num = 1 then 1 end) as Beginner,
sum(case when step_num = 2 then 1 end) as Intermediate,
sum(case when step_num = 3 then 1 end) as Expert
FROM steps
INNER JOIN locations ON steps.location_id = locations.id
GROUP BY locations.name
ORDER BY locations.name ASC
我如何还返回所有位置的总数?例如我想得到结果:
| LOCATION NAME | Beginner | Intermediate | Expert |
----------------------------------------------------
| Uptown | 5 | | 1 |
| Downtown | 2 | 1 | 3 |
| All locations | 7 | 1 | 4 |