0

我有一个包含以下列的表格:

+-------+------+-------+-------+-------+-------+
| age1  | val1 | age2  | val2  | age3  | val3  |
+-------+------+-------+-------+-------+-------+
| 30-40 | 34.5 | 41-50 | 32.01 | 51-60 | 29.13 |
+-------+------+-------+-------+-------+-------+

我想返回:

+-------+-------+
|  age  |  val  |
+-------+-------+
| 30-40 |  34.5 |
| 41-50 | 32.01 |
| 51-60 | 29.13 |
+-------+-------+

我最终使用 3 个这样的联合编写了一个大型查询,但这似乎不正确:

  select *
  from ( ... ) g1
  union
  select *
  from ( ... ) g2
  union
  select *
  from ( ... ) g3

有没有办法在没有混乱的情况下做到这一点?好像我错过了一些非常明显的东西。

4

1 回答 1

2

在 Postgres 中,您可以通过横向连接有效地将列取消透视到行:

select x.*
from mytable as t
cross join lateral (values 
    (t.age1, t.val1), 
    (t.age2, t.val2), 
    (t.age3, t.val3)
) as x(age, val)
于 2020-11-04T15:21:40.510 回答