【问题标题】:Combine multiple columns into a single column in Postgres在 Postgres 中将多列合并为一列
【发布时间】:2020-02-04 22:37:32
【问题描述】:

尝试编写一个查询,使现有的 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 

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

【问题讨论】:

    标签: sql database postgresql pivot unpivot


    【解决方案1】:

    在 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

    编号 |月 |数量 :- | :----- | --: 一个 |第 1 个月 | 2 一个 |第 2 个月 | 3 乙|第 1 个月 | 4 乙|第 2 个月 | 5

    【讨论】:

    • 欢迎@Alegna。如果我的回答正确回答了您的问题,请点击检查符号accept it...谢谢。
    【解决方案2】:

    使用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)
    

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2017-05-28
      • 2016-10-06
      • 2020-04-14
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多