Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

DECLARE @Temp TABLE 
(
    IntegerValue INT,
    Processed BIT
)

I have a solution that works for 3 rows but this is infelxable, if the requirements change then so would the query (ignoring the fact that my sum wouldnt work in this case).

@SumOfValues = (@FirstValue * @NumOfValues) + @NumOfValues 
like image 536
Ant Swift Avatar asked Sep 30 '11 09:09

Ant Swift


People also ask

How to temporarily store the number of consecutive rows in SQL?

The T-SQL code below uses a Common Table Expression (CTE) to temporarily store the rows where the DataValue exceeds 5 and a count of the number of consecutive rows. The bottom SELECT query returns those rows where the consecutiveValueCount is greater than or equal to 3.

How to get consecutive rows with the same date in SQL?

For the Tabibitosan method, assign each row an increasing number, ordered by the run date. When you subtract this from the run_date, consecutive rows have the same result. 9 rows selected.

How do you find the group identifier of a row in SQL?

Begin by applying the DENSE_RANK function to the rows. To produce the group identifier, we subtract the result of DENSE_RANK from the row value.

How to get statistics for consecutive rows in a table?

1 row (s) inserted. 9 rows selected. For the Tabibitosan method, assign each row an increasing number, ordered by the run date. When you subtract this from the run_date, consecutive rows have the same result. 9 rows selected. You can then group by this calculated value to get summary statistics.


1 Answers

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)
like image 113
Martin Smith Avatar answered Nov 10 '22 00:11

Martin Smith