简体   繁体   中英

Pivoting Data in PostgresSQL

I have a table as

Start Date sequence No Count Emp_id
old 0 1 1
2020-12-07 1 15 1
More 2 4 1
Total 3 20 1
old 0 15 2
2020-12-07 1 20 2
More 2 5 2
Total 3 40 2

I require output as

Emp_id Old 2020-12-07 More Total
1 1 15 4 20
2 15 20 5 40

Can someone please give me some idea or point in a direction on how can i achieve the desired output?

For a fixed list of values, you can use conditional aggregation:

select emp_id
    max(count) filter(where start_date = 'old'       ) as val_old,
    max(count) filter(where start_date = '2020-12-07') as val_2020_12_07,
    max(count) filter(where start_date = 'More'      ) as val_more,
    max(count) filter(where start_date = 'Total'     ) as val_total
from mytable
group by emp_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM