Search code examples
sqlpostgresqlunpivot

Pivoting rows to columns for each id


I want to pivot rows into columns in Postgres 10.

Here is the example data on db-fiddle:

enter image description here

I want to achieve the following output:

enter image description here


Solution

  • This is unpivoting and a lateral join is a convenient approach. Presumably, you want the ids to be the same in the result set as in the original data:

    select t.id, v.bin, v.sales
    from t cross join lateral
         (values ('bin1', bin1), ('bin2', bin2), ('bin3', bin3)
         ) v(bin, sales);
    

    Here is a db<>fiddle.