在PostgreSQL中将位字符串转换为数组

时间:2013-04-25 18:00:47

标签: arrays postgresql postgresql-9.2 bitstring

我有一个160个字符串的字符串,我需要一个整数数组来存储值为1的位的位置。

示例:

bitstring = '00110101'
array = [3,4,6,8]

是否可以仅使用SQL执行此操作,还是需要定义PL / SQL函数或类似的东西?

2 个答案:

答案 0 :(得分:5)

肯定可以用SQL编写它。这是一个起点:

select array(
  select substring(str from i for 1) as bit
  from generate_series(1, length(str)) as i
  where bit = '1'
);

但是,您可能希望将其包装在pl / sql函数中,以避免在整个地方重复代码。


工作职能:

create or replace function get_bit_positions(varbit) returns bit[] as $$
select array(
  select substring($1 from i for 1) as bit
  from generate_series(1, length($1)) as i
  where substring($1 from i for 1) = '1'
);
$$ language sql immutable;

答案 1 :(得分:5)

工作版:

WITH x AS (SELECT '00110101'::varbit AS b)
SELECT array_agg(i)
FROM  (SELECT b, generate_series(1, length(b)) AS i FROM x) y
WHERE  substring(b, i, 1) = '1';

varbit转换为text[]后更简单。转换为text并运行string_to_array()

然后你可以使用generate_subscripts()并按索引选择数组元素:

WITH x AS (SELECT string_to_array('00110101'::varbit::text, NULL) AS b)
SELECT array_agg(i)
FROM  (SELECT b, generate_subscripts(b,1) AS i FROM x) y
WHERE b[i] = '1'

this related question on dba.SE中的详细信息。