2015-10-07 51 views
0

範圍內,我試圖找到範圍以下問題如何找到在Oracle

我有(ID爲varchar(100),roll_no VARCHAR(100))與下面的值名爲my_tble表。

------------------- 
|id | roll_no | 
------------------- 
| 001 |  1 | 
| 002 |  2 | 
| 003 |  3 | 
| 004 |  4 | 
| 005 |  7 | 
| 006 |  8 | 
| 007 |  11 | 
| 008 |  15 | 
| 009 |  16 | 
| 010 |  17 | 
------------------- 

輸出應該是這樣:

----------- 
|roll_no | 
--------- 
| 1-4  | 
| 7-8  | 
| 11-11 | 
| 15-17 | 
----------- 
+0

MySQL和Oracle是不同的RDBMS! –

+0

這個結構顯示這是來自mysql –

回答

0
with base as (select 001 id, 1 roll_no from dual 
          union all 
          select 002 id, 2 roll_no from dual 
          union all 
          select 003 id, 3 roll_no from dual 
          union all 
          select 004 id, 4 roll_no from dual 
          union all 
          select 005 id, 7 roll_no from dual 
          union all 
          select 006 id, 8 roll_no from dual 
          union all 
          select 007 id, 11 roll_no from dual 
          union all 
          select 008 id, 15 roll_no from dual 
          union all 
          select 009 id, 16 roll_no from dual 
          union all 
          select 010 id, 17 roll_no from dual) 
select min(roll_no)||' - '|| max(roll_no) roll_no 
from (select roll_no 
      ,connect_by_root roll_no root 
      from base 
      connect by prior roll_no = roll_no-1 
      start with roll_no not in (select roll_no 
             from base b 
             where exists (select 1 
             from base b1 
             where b1.roll_no = b.roll_no-1))) 
group by root 
order by root 

SQL Fiddle

您也可以找到another approach with LAG analytic function