SQL - 计算一个属性,按另一个属性进行分组

时间:2018-02-21 22:45:53

标签: sql postgresql

我有一张表staff

staff
pt | ward
P  | 1
P  | 1
T  | 1
P  | 2
T  | 2

我想制作一张表格,计算每个病房的P和T的数量,如下所示:

staff
ward | P | T
1    | 2 | 1
2    | 1 | 1

我试过这个

WITH cte(ward, P, T) AS(
SELECT ward,
(SELECT COUNT(PT) FROM staff WHERE PT = 'P' ),
(SELECT COUNT(PT) FROM staff WHERE PT = 'T' ) FROM staff GROUP BY ward)
SELECT * FROM cte

然后我得到了这张桌子

staff
ward | P | T
1    | 3 | 2
2    | 2 | 2

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

案例陈述将在此处起作用:

SELECT
    ward,
    SUM(CASE WHEN pt = P THEN 1 ELSE 0 END) AS P,
    SUM(CASE WHEN pt = T THEN 1 ELSE 0 END) AS T
FROM
    table
GROUP BY
    ward

答案 1 :(得分:0)

使用条件聚合:

select ward, sum( (pt = 'P')::int ) as p, sum ( (pt = 'T')::int ) as t
from t
group by ward;