Postgresql row-to-column crosstab cross function error reporting and solution; No function matches the given name and arguments.

Postgresql row change column using crosstab

Need to install extension: extension

1. Error reporting

insert image description here

2. Solve

  1. install extension
CREATE EXTENSION tablefunc WITH SCHEMA <<YourSchema>>;
  1. 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;
    insert image description here

    The effect diagram is added as follows:
    insert image description here

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)
————————————————

reference

Guess you like

Origin blog.csdn.net/qq_40985985/article/details/128529843