Search code examples
sqlpostgresqlunpivot

SQL: "Reverse" transpose a table


I saw a lot of questions on transposing from the below table...

scanid | region | volume
-------------------------
1          A      34.4
1          B      32.1
1          C      29.1
2          A      32.4
2          B      33.2
2          C      35.6

to this table.

scanid | A_volume | B_volume | C_volume
----------------------------------------
1        34.4         32.1      29.1
2        32.4         33.2      35.6

However, I need to do the inverse, and have trouble trying to wrap my head around this problem. Can anyone help?

Thank you.


Solution

  • You could do this very simply with a UNION clause:

    Select Scan_ID, 'A' as Region, A_Volume as volume
        union all
    Select Scan_ID, 'B' as Region, B_Volume as volume
        union all
    Select Scan_ID, 'C' as Region, C_Volume as volume