Here is my data
id|col_name|value|
--+--------+-----+
1|col1 |ABC |
2|col2 |DEF |
2|col2 |FGH |
2|col2 |IJK |
3|col3 |MNO |
3|col3 |PQR |
3|col3 |STU |
3|col3 |XYZ |
And the expected output is
id Col1 Col2 col3
1 ABC DEF MNO
2 NULL FGH PQR
2 NULL IJK STU
2 NULL NULL XYZ
3 NULL NULL NULL
3 NULL NULL NULL
I tried this query shown here, but I get an exception:
ERROR: return and sql tuple descriptions are incompatible
This is the query I tried:
select
*
from
crosstab ('select id,col_name,value from hr.temp order by 1,2')
AS final_result(id int, col1 TEXT, col2 TEXT, col3 TEXT);
2
Answers
You are not exactly doing
PIVOT
, but ordering the values in three columns depending on their order, not some grouping criteria. Try something like this:Certainly not a plain case of
crosstab()
. This seems to fit the pattern:fiddle
But it’s really just a guess while the question is undefined.
And the order of rows is coincidental while (also) undefined.
With
ROWS UNBOUNDED PRECEDING
I slipped in a little secrete sauce to make it faster. See:This optimization will work automatically in Postgres 16. 🙂