My data looks like:
ID | Year | Volume1 | Volume2 |
---|---|---|---|
AAA | 2023 | 10 | 20 |
AAA | 2024 | 5 | 10 |
BBB | 2023 | 20 | 40 |
BBB | 2024 | 30 | 60 |
I would like to have the volumes per ID all on one row, where ideally the column names are extended with the year separated with an underscore sign.
What I want to have:
ID | Volume1_2023 | Volume2_2023 | Volume1_2024 | Volume2_2024 |
---|---|---|---|---|
AAA | 10 | 20 | 5 | 10 |
BBB | 20 | 40 | 30 | 60 |
How can I do this in PostgreSQL?
3
Answers
First, enable the tablefunc extension (if it’s not already enabled).
Then execute this query, replacing "your_table_name" with your actual table name:
The non cross tab pivot query approach here would be:
My suggestion is to aggregate years and volumes into a JSONB column.
DB Fiddle Demo