首页 > 解决方案 > 如何将列转换为行条件

问题描述

我有一个这样的列结构:

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中是否有类似的东西。

标签: sqlpostgresqlunpivot

解决方案


您可以使用未嵌套的数组:

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返回数组中值的索引。由于它对应于“索引”列,我们可以通过在输出中使用它来“重新创建”列名。

在线示例:https ://rextester.com/JJHG50564


推荐阅读