Postgresql row change column using crosstab
Need to install extension: extension
1. Error reporting
2. Solve
- install extension
CREATE EXTENSION tablefunc WITH SCHEMA <<YourSchema>>;
-
order by 1 is also required, it is very important~~ ensure that the same record can be merged, without order by the effect is as follows,
you can find that the same record without order is not merged;
The effect diagram is added as follows:
3. Source code
Reprinted from https://blog.csdn.net/moshowgame/article/details/127469331
-- by zhengkai.blog.csdn.net
create table sales(year int, month int, qty int);
insert into sales values(2022, 1, 1000);
insert into sales values(2022, 2, 1500);
insert into sales values(2022, 7, 500);
insert into sales values(2022, 11, 1500);
insert into sales values(2022, 12, 2000);
insert into sales values(2023, 1, 1200);
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
);
year | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
------+------+------+-----+-----+-----+-----+-----+-----+-----+-----+------+------
2022 | 1000 | 1500 | | | | | 500 | | | | 1500 | 2000
2023 | 1200 | | | | | | | | | | |
(2 rows)
————————————————