简体   繁体   中英

Combine multiple columns into a single column in Postgres

Trying to write a query that can make the existing Postgres table that looks like first set below to give a result of the second set here:

ID | Month1  | Month2
A  |    2    |   3   --(qty)
B  |    4    |   5   --(qty)

Result

ID  | Month  | QTY
A   | Month1 | 2
A   | Month1 | 3
B   | Month1 | 4
B   | Month1 | 5 

The best idea is to use multiple unions but that would be very long. Is there a more efficient way to get around this?

In Postgres, you can unpivot with a lateral join:

select t.id, m.month, m.qty
from mytable t
cross join lateral (values (t.Month1, 'Month1'), (t.Month2, 'Month2')) as m(qty, month)
order by t.id, m.month

Demo on DB Fiddle :

id | month  | qty
:- | :----- | --:
A  | Month1 |   2
A  | Month2 |   3
B  | Month1 |   4
B  | Month2 |   5

Another potential way to do it using generate_series :

select
  f.id,
  'Month' || i as month,
  case gs.i
    when 1 then f.month1
    when 2 then f.month2
  end as month
from
  foo f
  cross join generate_series (1, 2) gs (i)

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