我有一张桌子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
任何帮助都将不胜感激
最佳答案
案例陈述将在这里起作用:
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
关于sql - SQL-计算一个属性,按另一个属性分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48916812/