sql - 如何将列转换为行条件
问题描述
我有一个这样的列结构:
ID,c1(布尔),c2(布尔),c3(布尔),c4(布尔)。
如何在读取布尔值时将它们转换为行条件?我只想要真实的列。
IE
ID | c1 | c2 | c3 | c4 | c5
107 true true false true false
我只想返回这样的东西:
ID | col
1 c1
1 c2
1 c4
我不确定postgres中是否有类似的东西。
解决方案
您可以使用未嵌套的数组:
select id, 'c'||t.idx as col
from the_table
cross join unnest(array[c1,c2,c3,c4]) with ordinality as t(flag, idx)
where t.flag;
with ordinality
返回数组中值的索引。由于它对应于“索引”列,我们可以通过在输出中使用它来“重新创建”列名。
推荐阅读
- node.js - 树莓派在线模拟器?
- javascript - 角度 5 中的自定义管道不起作用
- android - Room 中的 RunInTransaction 方法
- python - 通过 Paramiko SFTP 上传文件不起作用
- python - 使用 python 模拟镜头光晕和色差
- java - 如何更改 Eclipse 显示设置?
- python-3.x - 作为脚本启动时,模块“子进程”没有属性“运行”
- ios - 在 swift 4 iOS 中截取整个 WebView 的屏幕截图
- reactjs - 在 ReactJS 中使用 .fetch() 上传文件
- facebook - 使用 react-native-fbsdk 分享视频