gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:15:59 24 4
gpt4 key购买 nike

我有一张 table 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 - 计算一个属性,按另一个分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com