How can I check a group of numbers are consecutive in T-SQL?

前端 未结 3 1963
面向向阳花
面向向阳花 2020-12-30 14:49

If i was to have a table with an integer column containing n number of rows and wanted to check if they were consecutive, how could I do this?

DECLA         


        
3条回答
  •  醉梦人生
    2020-12-30 15:34

    SELECT CASE
             WHEN COUNT(DISTINCT IntegerValue) /*Or COUNT(*) dependant on how
                                                duplicates should be treated */ 
                    =  1 + MAX(IntegerValue) - MIN(IntegerValue) THEN 'Y'
             ELSE 'N'
           END
    FROM   @Temp  
    

    If you want to know where the gaps are you can use

    ;WITH T AS
    (
    SELECT *,
           DENSE_RANK() OVER (ORDER BY IntegerValue) - IntegerValue AS Grp
    FROM @Temp
    )
    SELECT MIN(IntegerValue) AS RangeStart, 
           MAX(IntegerValue) AS RangeEnd
    FROM T
    GROUP BY Grp
    ORDER BY MIN(IntegerValue)
    

提交回复
热议问题