Postgres,将单行分成多行

Postgres, split single row into multiple rows

我有一个 table,其中的列如下:

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

我想return:

+-------+-------+
|  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

有没有办法做到这一点而不造成混乱?好像我错过了一些非常明显的东西。

在 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)