如何在oracle中对序列号进行分组?

bhu*_*ana 6 oracle

我有一个用逗号隔开多年的字符串.

例如2000,2001,2002,2005,2006,2007 and 2010.

我想将连续数字分组.

我的输出应该是2000-2003,2005-2007 and 2010.有没有办法在Oracle存储过程中执行此操作?

Kir*_*tev 0

18:42:15 SYSTEM@dwal> l
  1  with p as (
  2    select replace('2000,2001,2002,2005,2006,2007 and 2010',' and ',',') s, '[0-9]{4}' r from dual
  3  ), ex as (
  4    select regexp_substr(s,r, 1, level) as y
  5      from p
  6    connect by level <= regexp_count(s, r)
  7  ), grp as (
  8    select connect_by_root(y) s, y
  9      from ( select e1.y y, e2.y p from ex e1, ex e2 where e1.y - 1 = e2.y(+) )
 10   connect by prior y = p
 11     start with p is null
 12  ), agg as (
 13  select listagg(s||decode(max(y), s, null, '-'||max(y)), ',') within group (order by s) str
 14    from grp group by s
 15  )
 16* select regexp_replace(str, ',', ' and ', 1, regexp_count(str, ',')) result from agg
18:42:16 SYSTEM@dwal> /

RESULT
------------------------------
2000-2002,2005-2007 and 2010

Elapsed: 00:00:00.02
Run Code Online (Sandbox Code Playgroud)