Oracle:将连字符分隔的数值转换为逗号分隔范围

时间:2013-11-13 07:44:00

标签: oracle range hyphen

我正在使用Oracle

我有一个列名为SEQUENCE的表 其中包含以下格式的值:x,y,z,a-b

示例:

1)1,2,3,6-8,9-11

2)1,2,3,5,11

第一个例子是我遇到的问题。

我正在写一个选择查询,如:SELECT * from Table,其中Value IN(1,2,3,6-8,9-11)

为此,我想以这种格式转换HYPHEN值(6-8,9-22) 6,7,8,9,10,11 在此之后我的查询将是

SELECT * from Table where Value IN(1,2,3,6,7,8,9,10,11) 哪个会解决我的问题

我的问题是 如何实现这一目标 在ORACLE中将值(6-8,9-11)转换为(6,7,8,9,10,11)

1 个答案:

答案 0 :(得分:0)

还有一个选择

with str as
 (select '1,2,3,7-11' as ids from dual),
i as
 (select replace(trim(substr(t1.str,
                             t1.curr_pos + 1,
                             decode(t1.next_pos, 0, length(t1.str) + 2, t1.next_pos) - t1.curr_pos - 1)),
                 ' ',
                 '') as item
    from (select ids str,
                 decode(level, 1, 0, instr(ids, ',', 1, level - 1)) as curr_pos,
                 instr(ids, ',', 1, level) as next_pos
            from str
          connect by level <= length(ids) - length(replace(ids, ',', '')) + 1) t1),
ii as
 (select case
             when instr(item, '-') = 0 then
              item
             else
              substr(item, 1, instr(item, '-') - 1)
         end as first_item,
         case
             when instr(item, '-') = 0 then
              item
             else
              substr(item, instr(item, '-') + 1)
         end as last_item
    from i),
tmp_str as
 (select rownum as id,
         (select listagg(ii.first_item + level - 1, ',') within group(order by level)
            from dual
          connect by level <= ii.last_item - ii.first_item + 1) as ids
    from ii),
tmp_str2 as
 (select t.*, length(ids) - length(replace(ids, ',', '')) + 1 as cnt from tmp_str t),
tmp_dual as
 (select level as lv from dual connect by level <= (select max(cnt) as total_cnt from tmp_str2)),
tmp_str3 as
 (select *
    from (select id, lv, ids, cnt, row_number() over(partition by id order by lv) as rn from tmp_dual, tmp_str2) t1
   where rn <= cnt)
select distinct to_number(trim(substr(t1.str,
                                      t1.curr_pos + 1,
                                      decode(t1.next_pos, 0, length(t1.str) + 2, t1.next_pos) - t1.curr_pos - 1))) as id
  from (select ids str, decode(lv, 1, 0, instr(ids, ',', 1, lv - 1)) as curr_pos, instr(ids, ',', 1, lv) as next_pos
          from tmp_str3) t1
 order by 1

结果

1
2
3
7
8
9
10
11