postgresql - 在 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 很陌生,因此感谢您提供任何帮助。
谢谢!!
解决方案
对每一列使用 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 | |
推荐阅读
- javascript - Javascript 如何使文本变大 10%
- css - 壁纸在主题中调整和放大我的 Wordpress 登陆页面
- vb.net - 显示 MDI 子窗体后等待 - DoEvents 的替代方法
- distributed - 将 IPNS 链接添加到 ipfs-desktop
- python - 如何使用 selenium python 将具有不同属性的 Web 元素中的文本捕获到列表中
- python - WAV 文件 (.wav) 和 WAVE 音频文件 (.wave) 有什么区别?
- python - 我正在尝试在 django 中制作模型。但错误。为什么?
- c - 不通过C语言中的文件操作在c盘中创建txt文件
- php - 为什么我的 Symfony 5 本地服务器将 HTTP 请求显示为文本而不是呈现的页面?
- regex - 正则表达式匹配字符串(谷歌分析)