如何获取字符串中特定字符的所有位置索引?

时间:2019-06-12 16:54:47

标签: sql postgresql select

我正在使用postgres和PgAdmin3。我被困住了,甚至都不知道从哪里开始!

我有一列,其格式如下:

tvd_unit
YYNNNNNNNNNNNNNYYNNNNN

该列包含22个职位,这些职位通过是或否(是或否)表示行为在特定业务部门中是否处于活动状态

在上面的示例中,该参数仅以1、2、16和17单位有效。其余的都关闭了,我需要开发一个查询以返回参数处于活动状态的单位的每个数量,在上面的示例中,我需要返回:

1, 2, 16, 17

老实说,我不知道如何开始获取单位数量,我需要帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用generate_series和substr来获取字符串中的每个元素:

with data as (select 'YYNNNNNNNNNNNNNYYNNNNN' as tvd_unit)
select position,
       substr(tvd_unit, position, 1) as active
FROM data, 
     generate_series(1, length(tvd_unit), 1) g(position)
WHERE substr(tvd_unit, position, 1) = 'Y';
 position | active
----------+--------
        1 | Y
        2 | Y
       16 | Y
       17 | Y
(4 rows)

答案 1 :(得分:0)

解决问题的步骤如下。 您可以先构造一个字符串数组:

postgres=# select string_to_array(regexp_replace(replace(replace('YYNNNNNNNNNNNNNYYNNNNN','Y','Y,'),'N','N,'),',$',''),',') as arr;
                      arr                      
-----------------------------------------------
 {Y,Y,N,N,N,N,N,N,N,N,N,N,N,N,N,Y,Y,N,N,N,N,N}
(1 row)

然后将数组转换为多行,并为每行赋予一个排序号:

postgres=# with tmp as (                                                                                                           
select string_to_array(regexp_replace(replace(replace('YYNNNNNNNNNNNNNYYNNNNN','Y','Y,'),'N','N,'),',$',''),',') as arr
)
select
    unnest(arr) as letter,
    generate_series(1,array_length(arr,1),1) as sort
from
    tmp;
 letter | sort 
--------+------
 Y      |    1
 Y      |    2
 N      |    3
 N      |    4
 N      |    5
 N      |    6
 N      |    7
 N      |    8
 N      |    9
 N      |   10
 N      |   11
 N      |   12
 N      |   13
 N      |   14
 N      |   15
 Y      |   16
 Y      |   17
 N      |   18
 N      |   19
 N      |   20
 N      |   21
 N      |   22
(22 rows)

所需的最终完整SQL:

postgres=# with tmp as (                                                                                                           
select string_to_array(regexp_replace(replace(replace('YYNNNNNNNNNNNNNYYNNNNN','Y','Y,'),'N','N,'),',$',''),',') as arr
)
,tmp_2 as (
select
    unnest(arr) as letter,
    generate_series(1,array_length(arr,1),1) as sort
from
    tmp
)
select * from tmp_2 where letter = 'Y';
 letter | sort 
--------+------
 Y      |    1
 Y      |    2
 Y      |   16
 Y      |   17
(4 rows)

postgres=# with tmp as (
select string_to_array(regexp_replace(replace(replace('YYNNNNNNNNNNNNNYYNNNNN','Y','Y,'),'N','N,'),',$',''),',') as arr
)
,tmp_2 as (
select
    unnest(arr) as letter,
    generate_series(1,array_length(arr,1),1) as sort
from
    tmp
)
select letter,array_to_string(array_agg(sort),',') as result from tmp_2 where letter = 'Y' group by letter;
 letter |  result   
--------+-----------
 Y      | 1,2,16,17
(1 row)