使用位掩码从行生成多行

时间:2018-11-22 14:11:40

标签: sql postgresql

我们的表有3列:键,值和位掩码(如varchar;最大长度未知):

<div *ngFor="let value of [1,2,3]" class="css-{{value}}">
   DIV #{{value}}
</div>

是否可以编写查询,在输出中我将在位掩码中的键,值和abc | 23 | 101 xyz | 56 | 000101 的每种组合中得到一行,且该1的索引为整数列(不是从0还是1开始)?因此,例如上面的例子:

1

感谢任何想法!

1 个答案:

答案 0 :(得分:1)

我认为您最好为varchar选择最大长度。

SELECT * FROM
table 
INNER JOIN
generate_series(1,1000) s(n) 
ON 
  s.n <= char_length(bitmask) and 
  substring(bitmask from s.n for 1) = '1'

我们生成一个数字列表:

s.n
---
1
2
3
4
...

并以导致重复的表行的方式将其连接到表:

s.n bitmask
--- ------- 
1   000101
2   000101
3   000101
4   000101
5   000101
6   000101
1   101
2   101
3   101

然后使用s.n对位掩码进行子串化,并寻找等于1的位置:

s.n bitmask substr
--- ------- ------
1   000101  --substring('000101' from 1 for 1) = '1'? no
2   000101  --substring('000101' from 2 for 1) = '1'? no
3   000101  --substring('000101' from 3 for 1) = '1'? no
4   000101  --substring('000101' from 4 for 1) = '1'? yes...
5   000101
6   000101
1   101
2   101
3   101

因此s.n为我们提供了所需输出的最后一列中的数字,而where仅过滤出字符串子字符串有效的行

相关问题