SQL:连接顺序整数值

时间:2013-07-31 14:04:19

标签: sql oracle

我有一个这样的专栏:

ID
--------
1
2
3
4
5
7
10

我希望获得以下结果集:

ID
--------
1-5
7
10

有没有办法只用(Oracle)SQL实现这个目的?

2 个答案:

答案 0 :(得分:7)

是:

select (case when min(id) < max(id)
             then cast(min(id) as varchar2(255)) || '-' || cast(max(id) as varchar2(255))
             else cast(min(id) as varchar2(255))
        end)
from (select id, id - rownum as grp
      from t
      order by id
     ) t
group by grp
order by min(id);

Here是一个证明它的SQL小提琴。

查询背后的想法是从一系列数字中减去rownum会产生一个常数。您可以使用常量进行分组。

答案 1 :(得分:0)

自我加入是必要的...我认为这将有效

Select a.id, b.id
From table a   -- to get beginning of each range
  Join table b -- to get end of each range
    On b.id >= a.Id -- guarantees that b is after a
       And Not exists (Select * From table m  -- this guarantees all values between 
                       where id Between a.id+1 and b.id
                           And Not exists(Select * From table 
                                          Where id = m.id-1))
       And Not exists (Select * From table  -- this guarantees that table a is start 
                       Where id = a.id -1)
       And Not exists (Select * From table  -- this guarantees that table b is end
                       Where id = b.id + 1)