How to find the boundaries of groups of contiguous sequential numbers?

后端 未结 1 1195
无人共我
无人共我 2020-12-01 08:32

I have a table with the following definition

CREATE TABLE mytable
  (
     id     INT IDENTITY(1, 1) PRIMARY KEY,
     number BIGINT,
     status INT
  )


        
相关标签:
1条回答
  • 2020-12-01 09:20

    As mentioned in the comments this is a classic gaps and islands problem.

    A solution popularized by Itzik Ben Gan is to use the fact that ROW_NUMBER() OVER (ORDER BY number) - number remains constant within an "island" and cannot appear in multiple islands.

    WITH T
         AS (SELECT ROW_NUMBER() OVER (ORDER BY number) - number AS Grp,
                    number
             FROM   mytable
             WHERE  status = 0)
    SELECT MIN(number) AS [From],
           MAX(number) AS [To]
    FROM   T
    GROUP  BY Grp
    ORDER  BY MIN(number) 
    

    NB: If number is not guaranteed to be unique replace ROW_NUMBER with DENSE_RANK in the code above.

    0 讨论(0)
提交回复
热议问题