PSQL按同一行上的多个条件进行分组

时间:2019-06-04 07:43:18

标签: sql database group-by count psql

假设我有一个这样的表:

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或类似于DB的表。 预先感谢

3 个答案:

答案 0 :(得分:1)

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

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;

答案 1 :(得分:0)

您可以UNIONSELECT作为红色,蓝色值,并获得红色,蓝色MAX()的{​​{1}}值

GROUP BY letter

答案 2 :(得分:0)

您可以尝试对Letter进行分组以分别获取计数,然后加入

select T1.Letter, CASE WHEN Red is NULL THEN 0 ELSE Red END AS Red , CASE WHEN Blue is NULL THEN 0 ELSE Blue END AS Blue   
from 
(select Letter, count(*) as Red from letters where Color = 'Red' group by Letter) T1 
full join 
(select Letter, count(*) as Blue from letters where Color = 'Blue' group by Letter) T2 
on T1.Letter = T2.Letter;