Home > Net >  Column values as rows in Postgres
Column values as rows in Postgres

Time:12-01

I have a table called price and it has columns like Item , Price_01, Price_02, Price_03, Price_04 and table data is as follows.

Item , Price_01, Price_02, Price_03, Price_04
Bat  , 1000 , 1100, 1200 , 1300
Ball  , 11000 , 1200, 1300 , 1400

My requirement is, i want to get Price columns data as rows for the given input Item. For example, Item input is Bat then output should be like

1000
1100
1200
1300

How can i do this in Postgres. Is there any alternate for PIVOT in Postgres

CodePudding user response:

That's an UNPIVOT, not PIVOT and it can be done using a VALUES clause in Postgres:

select p.item, 
       v.price
from price p
  cross join lateral (
     values (p.price_01), (p.price_02), (p.price_03), (p.price_04) 
  ) as v(price)
where p.item = 'Bat'
  • Related