'Postgres convert long to wide format
Apologies if this question has been answered before, feel free to point it to me, but I can't find a basic, clean answer for (what I feel like should be) a relatively basic question.
I want to convert a postgres table from long to wide format.
Imagine I have a table...
| date | value | id |
|---|---|---|
| 2022-01-01 | 100 | 1 |
| 2022-01-02 | 200 | 1 |
| 2022-01-03 | 300 | 1 |
| 2022-01-01 | 100 | 2 |
| 2022-01-02 | 200 | 2 |
| 2022-01-03 | 300 | 2 |
| 2022-01-01 | 100 | 3 |
| 2022-01-02 | 200 | 3 |
| 2022-01-03 | 300 | 3 |
And I want to output it as...
| date | id_1_value | id_2_value | id_3_value |
|---|---|---|---|
| 2022-01-01 | 100 | 100 | 100 |
| 2022-01-02 | 200 | 200 | 200 |
| 2022-01-03 | 300 | 300 | 300 |
If you're going to answer though, I want to make it very clear that the way in which you convert the ids to columns needs to be dynamic. For example, if I am doing this to a table with 100 different ids that I do not know before hand, the solution should be able to elegantly handle this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
