-5

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

kimi
  • 525
  • 5
  • 17

1 Answers1

0

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786