It is currently in a monthly report. I want it to have 4 quarters Q1, Q2, Q3, Q4 instead of Jan, Feb, Mar, Apr, May, Jun, Jul, etc.
Here is the code:
create table sales(year int, month int, qty int);
insert into sales values(2007, 1, 1000);
insert into sales values(2007, 2, 1500);
insert into sales values(2007, 7, 500);
insert into sales values(2007, 11, 1500);
insert into sales values(2007, 12, 2000);
insert into sales values(2008, 1, 1000);
select * from crosstab(
'select year, month, qty from sales order by 1',
'select m from generate_series(1,12) m'
) as (
year int,
"Jan" int,
"Feb" int,
"Mar" int,
"Apr" int,
"May" int,
"Jun" int,
"Jul" int,
"Aug" int,
"Sep" int,
"Oct" int,
"Nov" int,
"Dec" int
);
I would just use conditional aggregation:
select year,
sum(qty) filter (where month between 1 and 3) as q1,
sum(qty) filter (where month between 4 and 6) as q2,
sum(qty) filter (where month between 7 and 9) as q3,
sum(qty) filter (where month between 10 and 12) as q4
from t
group by year;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.