Postgresql 在postgres中分组时旋转

Postgresql 在postgres中分组时旋转,postgresql,group-by,sum,pivot,postgres-crosstab,Postgresql,Group By,Sum,Pivot,Postgres Crosstab,我一直在postgres中使用交叉表来透视表,但现在需要添加一个分组,我不确定这是否可行 我从这样的结果开始: Date Account# Type Count ----------------------------------------- 2020/1/1 100 Red 5 2020/1/1 100 Blue 3 2020/1/1 100 Yel

我一直在postgres中使用交叉表来透视表,但现在需要添加一个分组,我不确定这是否可行

我从这样的结果开始:

Date          Account#    Type   Count  
-----------------------------------------
2020/1/1         100      Red       5   
2020/1/1         100      Blue      3   
2020/1/1         100      Yellow    7
2020/1/2         100      Red       2 
2020/1/2         100      Yellow    9  
2020/1/1         101      Red       4   
2020/1/1         101      Blue      7   
2020/1/1         101      Yellow    3
2020/1/2         101      Red       8
2020/1/2         101      Blue      6 
2020/1/2         101      Yellow    4       

我想这样做,每个日期和帐户的组合都有一行:

我编写的代码返回错误“提供的SQL必须返回3列:rowid、category和values”,根据我对交叉表的理解,这是有意义的

SELECT * 
FROM crosstab(
SELECT date, account_number, type, count
FROM table
ORDER BY 2,1,3'
) AS ct (date timestamp, account_number varchar, Red bigint, Blue bigint, Yellow bigint);
(我在示例表中以简化格式编写了日期,但它们是时间戳)


有没有其他方法可以使第一个表看起来像第二个表?谢谢大家!

您可以执行条件聚合:

select
    date,
    account#,
    sum(cnt) filter(where type = 'Red'   ) red,
    sum(cnt) filter(where type = 'Blue'  ) blue,
    sum(cnt) filter(where type = 'Yellow') yellow
from mytable
group by date, account#

您可以执行条件聚合:

select
    date,
    account#,
    sum(cnt) filter(where type = 'Red'   ) red,
    sum(cnt) filter(where type = 'Blue'  ) blue,
    sum(cnt) filter(where type = 'Yellow') yellow
from mytable
group by date, account#