我有一个psql表
Points
id (SERIAL) | user(INTEGER) | time_of_point(TIMESTAMP) | title (TEXT)
我想对用户积分进行细分,以显示其当前月份,当前年份和寿命。
我对如何执行此操作有些迷茫。查询是什么样的?
决赛桌应该像这样
User | Points (this month) | Points (this year) | Lifetime Points
1 | 5 | 10 | 216
2 | 7 | 14 | 125
3 | 15 | 140 | 325
答案 0 :(得分:1)
条件聚合怎么样?
select user,
sum(points) filter (where date_trunc('month', time_of_point) = date_trunc('month', now()) as this_month,
sum(points) filter (where date_trunc('year', time_of_point) = date_trunc('year', now()) as this_year,
sum(points) as lifetime
from t
group by user;