I am trying to find the range in following problem
I have a table named my_tble(id varchar(100),roll_no varchar(100)) with following values.
-------------------
|id | roll_no |
-------------------
| 001 | 1 |
| 002 | 2 |
| 003 | 3 |
| 004 | 4 |
| 005 | 7 |
| 006 | 8 |
| 007 | 11 |
| 008 | 15 |
| 009 | 16 |
| 010 | 17 |
-------------------
Output should be in this way:
-----------
|roll_no |
---------
| 1-4 |
| 7-8 |
| 11-11 |
| 15-17 |
-----------
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
Also you can find another approach with LAG analytic function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.