首页 > 解决方案 > 在 postgresql 中拆分列并获取新表

问题描述

我在 postgresql 中有一个这样的表:

Time  | id/type  | value

1        A/a       10
2        A/b       15
3        A/c       8
4        A/b       2

我想转换成一个带有布局的new_table:

Time  | id  | a  | b  | c

1      A   10    Null   Null 
2      A   Null  15     Null
3      A   Null  Null    8
4      A   Null  2      Null

你能帮我解决这个问题吗?总的来说,我对 Sql 很陌生,因此感谢您提供任何帮助。

谢谢!!

标签: postgresqldatatable

解决方案


对每一列使用 CASE 表达式:

select "Time", split_part("id/type", '/', 1) id,
  case when split_part("id/type", '/', 2) = 'a' then "value" end a,
  case when split_part("id/type", '/', 2) = 'b' then "value" end b,
  case when split_part("id/type", '/', 2) = 'c' then "value" end c
from tablename

请参阅演示
结果:

| Time | id  | a   | b   | c   |
| ---- | --- | --- | --- | --- |
| 1    | A   | 10  |     |     |
| 2    | A   |     | 15  |     |
| 3    | A   |     |     | 8   |
| 4    | A   |     | 2   |     |

推荐阅读