gpt4 book ai didi

sql - PSQL 在同一行上按多个条件分组

转载 作者:搜寻专家 更新时间:2023-10-30 23:26:37 25 4
gpt4 key购买 nike

假设我有一个这样的表:

Letter  Color  
A Red
A Blue
B Red
C Red
C Red

我想要实现的是以下输出格式:

Letter   Red   Blue
A 1 1
B 1 0
C 2 0

尝试如下:

SELECT letter, red, blue FROM (
SELECT letter, count(*) AS red from letters where color = 'red'
GROUP BY letter
UNION
SELECT letter, count(*) AS blue from letters where color = 'blue'
GROUP BY letter
) GROUP BY letter

有人可以帮忙吗?请注意,我不能添加任何 tablefunc 或类似的数据库。提前致谢

最佳答案

我认为最简单的方法是条件聚合:

select letter,
sum(case when color = 'Red' then 1 else 0 end) as red,
sum(case when color = 'Blue' then 1 else 0 end) as blue
from letters
group by letter
order by letter;

关于sql - PSQL 在同一行上按多个条件分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439451/

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