-1

I need to use pivot in postgres, below is the base table

enter image description here

Below is the desired output

enter image description here

Please help me with the query.

1

2 Answers 2

1

This is actually an un-pivot, not pivot

select year, week, 'loading' as area, loading as value
from the_table
union all
select year, week, 'picking', picking
from the_table
union all
select year, week, 'painting', painting
from the_table
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much.. saved me
0

If you have only 3 columns which you need to pivot, then use union

select year,week,'loading' as aread,loading as val from tbl
union all
select year,week,'painting' as area,painting as val from tbl
union all
select year,week,'picking' as area,picking as val from tbl

If the number of column is dynamic, then I 'd suggest you to use dynamic pivot.

Dynamic pivot query using PostgreSQL 9.3

http://www.cureffi.org/2013/03/19/automatically-creating-pivot-table-column-names-in-postgresql/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.