Postgres,将单行拆分为多行

时间:2020-11-04 15:13:37

标签: sql postgresql unpivot lateral-join

我有一个带有类似列的表:

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

有没有办法做到这一点?似乎我遗漏了一些明显的东西。

1 个答案:

答案 0 :(得分:1)

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

# without -Raw you get the content as string array
$body = (Get-Content -Path 'C:\log.log') -join '<br />'
Send-MailMessage -Body $body -BodyAsHtml ...