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
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With