Skip to content
Advertisement

How to break sequence

i have a table named sequence with a single column val and table looks like

val
-----
1
2
3
5
8
9
10

i need to identify the range of numbers if there is a break in sequence and output like

range_start    range_end
-----------    ----------
1              3
5              5
8              10

Advertisement

Answer

Subtract an increasing sequence and you’ll get a constant for values that are in sequence. Then aggregate:

select min(val), max(val)
from (select val, row_number() over (order by val) as seqnum
      from t
     ) t
group by (val - seqnum);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement