簡體   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