Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 985891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T05:14:06+00:00 2026-05-16T05:14:06+00:00

I need to collapse multiple ranges of sequential numbers (1 or more) to sets

  • 0

I need to collapse multiple ranges of sequential numbers (1 or more) to sets of their minimum and maximum values. I have unique integers (no duplicates) stored in a table column.

The obvious way (to me) to solve this problem is to use a cursor (see my algorithm below) and iterate through every integer. However, it seems inefficient to me so I am wondering if there is a more efficient algorithm. Perhaps there is a way using common table expressions with recursion. I have more than 32767 integers though, so any solution will need to use option (MAXRECURSION 0) which sets unlimited recursion.

Following is a simplified test case for my existing algorithm usign a cursor. It will output the minimum and maximum for each range of sequential numbers (e.g. 1-3, 9-11, 13-13, 15-16).

I am using MS SQL Server 2008. Please note comments begin with two dashes (–).

declare @minInt int, @maxInt int
declare @nextInt int, @prevInt int
--need a temporary table to store the ranges that were found
declare @rangeTable table (minInt int, maxInt int)
declare mycursor cursor for
select * from
(
    select 1 as id  union
    select 2 as id  union
    select 3 as id  union
    select 9 as id  union
    select 10 as id union
    select 11 as id union
    select 13 as id union
    select 15 as id union
    select 16 as id
) tblRanges
order by id--order is needed for this algorithm if used with generic data
open mycursor
--initialise new sequence
fetch next from mycursor into @minInt
select @maxInt = @minInt--set the min and max to the smallest value
select @prevInt = @minInt--store the last int
declare @sequenceFound int
while @@FETCH_STATUS=0
begin

    select @sequenceFound=1--set the default flag value to true
    --loop while sequence found
    while @@FETCH_STATUS=0 and @sequenceFound = 1
    begin

        fetch next from mycursor into @nextInt
        if @nextInt = (@prevInt + 1)
        begin
            select @sequenceFound = 1
        end
        else
        begin
            select @sequenceFound = 0
        end
        select @prevInt = @nextInt--store the current value as the previous value for the next comparison
        if @sequenceFound = 1 --if the nextInt is part of a sequence, then store the new maxInt
            and @maxInt < @nextInt--should always be true for ordered output containing no duplicates
        begin
            select @maxInt = @nextInt
        end

    end--while sequenceFound
    --store the sequence range and then check for more sequences
    insert into @rangeTable (minInt,maxInt) values (@minInt,@maxInt)
    --store the current value as the new minInt and maxInt for the next sequence iteration
    select @minInt = @nextInt
    select @maxInt = @nextInt
end--while more table rows found
select * from @rangeTable

close mycursor
deallocate mycursor
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T05:14:07+00:00Added an answer on May 16, 2026 at 5:14 am

    Courtesy of Itzik Ben-Gan:

    WITH tblRanges AS
    ( 
        SELECT 1 AS ID  UNION 
        SELECT 2 AS ID  UNION 
        SELECT 3 AS ID  UNION 
        SELECT 9 AS ID  UNION 
        SELECT 10 AS ID UNION 
        SELECT 11 AS ID UNION 
        SELECT 13 AS ID UNION 
        SELECT 15 AS ID UNION 
        SELECT 16 AS ID 
    ),
    StartingPoints AS
    (
    SELECT ID, ROW_NUMBER() OVER(ORDER BY ID) AS rownum
    FROM tblRanges AS A
    WHERE NOT EXISTS
    (SELECT *
    FROM tblRanges AS B
    WHERE B.ID = A.ID - 1)
    ),
    EndingPoints AS
    (
    SELECT ID, ROW_NUMBER() OVER(ORDER BY ID) AS rownum
    FROM tblRanges AS A
    WHERE NOT EXISTS
    (SELECT *
    FROM tblRanges AS B
    WHERE B.ID = A.ID + 1)
    )
    SELECT S.ID AS start_range, E.ID AS end_range
    FROM StartingPoints AS S
    JOIN EndingPoints AS E
    ON E.rownum = S.rownum;
    

    You can read a full explanation from his chapter in SQL Sever MVP Deep Dives called Gaps and Islands. He explains various techniques (including cursors) and compares them in terms of performance.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose that I have a multimap (which maps multiple values to a single key),
I have a WPF ListView within a ScrollViewer. I need to collapse the ListView
I have an SSRS report where I need to collapse data into a summary
I have an unusual project that I need to display large sets of questions
I need a way to collapse duplicate (defined in terms of a string field
I need to add some accordian style expand/collapse handles to a series of parent
Need some help, please. I have a line of horizontal thumbnails loaded as ONE
Need to use own imaged markers instead built-in pins. I have several questions. 1.
need a quick help here. I have a series of hyperlinks all with the
I want to make the div's expand/collapse on the jquery click function I have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.