I have the following PostgreSQL table:
create table companies (
id bigserial primary key,
created_at timestamp(6),
name varchar(200),
status varchar(200)
);
I would like to split the result by month and to pass the months by param.
How I can get the following result using SQL query:
created_at | Active | Blocked |
---|---|---|
2023-8-07 18:06:56.000000 | 54 | 32 |
2023-5-07 18:06:56.000000 | 51 | 13 |
2023-12-07 18:06:56.000000 | 35 | 35 |
2
Answers
You can use
date_trunc()
in combination with an aggregatefilter
clause: demoIt subtracts the custom month start, aligns the result to the beginning of the month, restores the start point. If
created_at
was on or after that custom start point, it’ll stay in its month. Otherwise it’ll be assigned to the previous one.Based on this:
It returns this:
so you want to group by month and count on each month how many are active and how many are blocked?
you can do this with
if you want to group it based on year-month:
hope this helps