Skip to content
Advertisement

Postgres Counts based on Month and Years

I have a psql table

Points
id (SERIAL) | user(INTEGER) | time_of_point(TIMESTAMP) | title (TEXT)

I want to get a break down of users points that shows their points the current month, current year, and the lifetime.

I’m a bit lost on how to do this. What would the query look like?

The final table should look like this

User | Points (this month) | Points (this year) | Lifetime Points
1    |     5               |     10             |     216
2    |     7               |     14             |     125
3    |    15               |    140             |     325

Advertisement

Answer

How about conditional aggregation?

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;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement