Quantcast
Channel: Answers for "Selecting multiple ranges from a set of dates"
Viewing all articles
Browse latest Browse all 12

Answer by Phil Factor

$
0
0
I've made the test data a little bit more realistic as it has an error overlapping a second boundary. This solution relies on the data being inserted into the heap in datetime order declare @Dt table (TestDate DateTime, contiguity int) insert into @dt (testdate) values (convert(datetime,'26/07/2010 1:00:03',103)), (convert(datetime,'26/07/2010 1:00:04',103)), (convert(datetime,'26/07/2010 1:00:05',103)), (convert(datetime,'26/07/2010 1:00:06',103)), (convert(datetime,'26/07/2010 1:00:07',103)), (convert(datetime,'26/07/2010 1:00:25',103)), (convert(datetime,'26/07/2010 1:00:50',103)), (convert(datetime,'26/07/2010 1:00:51',103)), (convert(datetime,'26/07/2010 1:00:52',103)), (convert(datetime,'26/07/2010 1:00:53',103)), (convert(datetime,'26/07/2010 1:00:54',103)), (convert(datetime,'26/07/2010 1:00:55',103)), (convert(datetime,'26/07/2010 1:00:56',103)), (convert(datetime,'26/07/2010 1:00:57',103)), (convert(datetime,'26/07/2010 1:00:58',103)), (convert(datetime,'26/07/2010 1:00:59',103)), (convert(datetime,'26/07/2010 1:01:00',103)), (convert(datetime,'26/07/2010 1:01:01',103)), (convert(datetime,'26/07/2010 1:01:02',103)), (convert(datetime,'26/07/2010 1:01:03',103)), (convert(datetime,'26/07/2010 1:01:04',103)), (convert(datetime,'26/07/2010 1:50:37',103)), (convert(datetime,'26/07/2010 1:50:38',103)), (convert(datetime,'26/07/2010 1:50:39',103)), (convert(datetime,'26/07/2010 1:50:40',103)), (convert(datetime,'26/07/2010 1:50:41',103)), (convert(datetime,'26/07/2010 1:50:42',103)), (convert(datetime,'26/07/2010 1:50:43',103)), (convert(datetime,'26/07/2010 1:50:44',103)), (convert(datetime,'27/07/2010 2:20:37',103)), (convert(datetime,'27/07/2010 2:20:38',103)), (convert(datetime,'27/07/2010 2:20:39',103)), (convert(datetime,'27/07/2010 2:20:40',103)), (convert(datetime,'27/07/2010 2:20:41',103)), (convert(datetime,'27/07/2010 2:20:42',103)), (convert(datetime,'27/07/2010 2:20:43',103)), (convert(datetime,'27/07/2010 2:20:44',103)) DECLARE @LastDate DATETIME , @Contiguity INT SELECT @LastDate = '1 Jan 2010' , @Contiguity = 0 UPDATE @dt SET @Contiguity = contiguity = CASE WHEN DATEDIFF(second, @LastDate, TestDate) <= 1 THEN @Contiguity ELSE @Contiguity + 1 END , @LastDate = TestDate SELECT MIN(TestDate) , MAX(TestDate) FROM @dt GROUP BY contiguity HAVING COUNT(*) > 1 /* ----------------------- ----------------------- 2010-07-26 01:00:03.000 2010-07-26 01:00:07.000 2010-07-26 01:00:50.000 2010-07-26 01:01:04.000 2010-07-26 01:50:37.000 2010-07-26 01:50:44.000 2010-07-27 02:20:37.000 2010-07-27 02:20:44.000 (4 row(s) affected) */

Viewing all articles
Browse latest Browse all 12

Trending Articles