简体   繁体   English

在 Postgres 中将多列合并为一列

[英]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:尝试编写一个查询,可以使现有的 Postgres 表看起来像下面的第一组,以在此处给出第二组的结果:

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:在 Postgres 中,您可以使用横向连接进行反旋转:

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 : 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 :另一种使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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