繁体   English   中英

在 Postgres 中将多列合并为一列

[英]Combine multiple columns into a single column in Postgres

尝试编写一个查询,可以使现有的 Postgres 表看起来像下面的第一组,以在此处给出第二组的结果:

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

结果

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

最好的想法是使用多个联合,但这会很长。 有没有更有效的方法来解决这个问题?

在 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

DB Fiddle 上的演示

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

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