Sql 在Postgres中将多个列合并为一个列
正在尝试编写一个查询,使现有的Postgres表看起来像下面的第一个集,从而在此处给出第二个集的结果:Sql 在Postgres中将多个列合并为一个列,sql,database,postgresql,pivot,unpivot,Sql,Database,Postgresql,Pivot,Unpivot,正在尝试编写一个查询,使现有的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 最好的办法是使用多个联合体,但这将是非常漫长的。有
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中,您可以通过侧向连接取消PIVOT:
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
:
id | month | qty
:- | :----- | --:
A | Month1 | 2
A | Month2 | 3
B | Month1 | 4
B | Month2 | 5
id |月|数量
:- | :----- | --:
A |月1 | 2
A |月2 | 3
B |月1 | 4
B |月2 | 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)
欢迎@Alegna。如果我的回答正确地回答了您的问题,那么请单击复选标记。。。谢谢