首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Oracle :将连字符分隔的数值转换为逗号分隔的范围

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

Stack Overflow用户
提问于 2013-11-13 15:44:00
回答 1查看 1K关注 0票数 0

我正在使用Oracle

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

示例:

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

2) 1,2,3,5,11

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

我正在编写一个select查询,如: SELECT * from Table where Value IN (1,2,3,6-8,9-11)

为此,我希望将连字符的值(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)这样的转换值

EN

回答 1

Stack Overflow用户

发布于 2013-11-13 17:24:49

还有一项选择

代码语言:javascript
运行
复制
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

结果

代码语言:javascript
运行
复制
1
2
3
7
8
9
10
11
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19948136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档