Skip to content
Advertisement

How to transpose column to row and duplicate the original column header?

I have a table for example as below, the alphabet is header and the numbers are its records

I want to transpose the table to be like below:

This is not just transposing from col to row, but I also need to copy the alphabet header to as many as the original row (If I have 2 original rows then I need to copy the header twice, if I have 3 then I have to copy 3 times). I’m new in postgresql, how to achieve this?

Advertisement

Answer

Use a lateral join:

Compared to the union all approach, this only scans the table once. This can be a bit performance win if your “table” is really a more complex query.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement