PostgreSQL 按月和类型分组数据
PostgreSQL group data by month AND type
我有一个 table 是这样的:
ID item_type date
1 apple 2016-12-01
2 banana 2016-12-01
3 banana 2016-12-01
等等。我需要做的是得到一个输出 table 以月份为行,以 item_type 为列,以及每个组合的条目数,使其看起来像
month apple banana
dec 1 2
等等...我已经尝试 date_trunc
进行每月分组,但这似乎是根据日期而不是月份给我计数!而且我完全不知道如何进行多重分组。
使用条件聚合:
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;
不相关的提示,但我也不会使用 "date" 作为列名,因为它是 pgsql 中的保留字。
顺便说一句,如果我没记错的话,查询应该是这样的:
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" 存储为字符串变量。
我有一个 table 是这样的:
ID item_type date
1 apple 2016-12-01
2 banana 2016-12-01
3 banana 2016-12-01
等等。我需要做的是得到一个输出 table 以月份为行,以 item_type 为列,以及每个组合的条目数,使其看起来像
month apple banana
dec 1 2
等等...我已经尝试 date_trunc
进行每月分组,但这似乎是根据日期而不是月份给我计数!而且我完全不知道如何进行多重分组。
使用条件聚合:
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;
不相关的提示,但我也不会使用 "date" 作为列名,因为它是 pgsql 中的保留字。
顺便说一句,如果我没记错的话,查询应该是这样的:
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" 存储为字符串变量。