This is a gaps and islands problem
WITH Src AS (
SELECT SampleDate, SampleValue,
ROW_NUMBER() OVER(ORDER BY SampleDate) -
ROW_NUMBER() OVER(PARTITION BY SampleValue ORDER BY SampleDate) AS grp
FROM #SampleRanges
)
SELECT MIN(SampleDate) AS RangeStartDate,
MAX(SampleDate) AS RangeEndDate,
SampleValue,
COUNT(*) AS ValueCount
FROM Src
GROUP BY grp,SampleValue
ORDER BY RangeStartDate;
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537
September 3, 2019 at 3:26 pm
Brilliant. Great solution
I knew I'd come across this before, but "gaps and islands" are terms I'd forgotten , so I can now search properly for this type of problem.
September 4, 2019 at 9:04 am
Viewing 3 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply