SQL Query - Find block of sequential numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ruileote
    New Member
    • Apr 2014
    • 1

    SQL Query - Find block of sequential numbers

    Hi, I have a problem. In my databse I have the following numbers available:
    101
    104
    105
    110
    111
    112
    113
    114
    What I need is to get a select query with records and sequentials numbers after it like:
    101 0
    104 1 (the number 105)
    105 0
    110 4 (the numbers 111,112,113,114 )
    111 3 (the numbers 112,113,114)
    112 2 (the numbers 113,114)
    113 1 (the numbers 114)
    114 0
    How can I do It?
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    Please, dont ask for an explanation, but next quesy seems to give the answer (with above sample data!!)

    Code:
    select a, case when e>d then 1 else d end b 
    from (
    	select x.a, x.b, x.c, (select count(*) from test05 where i between x.b and x.c) d, x.c-x.b e  
    	from (
    		select 
    			x1.i a, 
    			(select min(i) from test05 where test05.i>x1.i) b, 
    			(select max(m5.i) from test05 m5 where m5.i>=x1.i and exists(select t.i from test05 t where t.i=x1.i+1)  ) c
    		from test05 x1 
    		)x
    	) y

    Comment

    Working...