按月和类型的PostgreSQL组数据

时间:2016-12-13 16:20:04

标签: sql postgresql pivot crosstab

我有一张类似这样的表:

ID    item_type    date
1      apple        2016-12-01       
2      banana       2016-12-01      
3      banana       2016-12-01  

等等。我需要做的是获取一个输出表,其中月份为行,item_type为列,以及每个组合的条目数,使其看起来像

month    apple     banana       
dec      1         2

依此类推......我已经尝试date_trunc进行月度分组,但这似乎是根据日期而非月份来计算!而且我不确定如何进行多重分组。

3 个答案:

答案 0 :(得分:4)

使用条件聚合:

select date_trunc('month', date) as mon,
       sum((item_type = apple)::int) as apple,
       sum((item_type = banana)::int) as banana
from t
group by mon
order by mon;

答案 1 :(得分:1)

不相关的提示,但我也不会使用“date”作为列名,因为它是pgsql中的保留字。

答案 2 :(得分:0)

不过,如果我没记错的话,查询应该是这样的:

select date_trunc('month', date) as mon,
       sum((item_type = 'apple')::int) as apple,
       sum((item_type = 'banana')::int) as banana
from t
group by mon
order by mon;

为避免Postgres发出错误,因为我假设“item_type”存储为字符串变量。