Running SQL Server 2016 Express.
I have this table with sample data:
ID Datetime2 other columns
------------------------------------------
1 2017-01-14 11:00:00 ...
1 2017-01-14 11:01:00 ...
1 2017-01-14 11:02:00 ...
1 2017-01-14 11:03:00 ...
1 2017-01-14 11:10:00 ... --> 7 minutes gap
1 2017-01-14 11:11:00 ...
1 2017-01-14 11:20:00 ... --> 9 minutes gap
1 2017-01-14 11:22:00 ...
1 2017-01-14 11:24:00 ...
I want to have this kind of result
ID start end other columns
-----------------------------------------------------------
1 2017-01-14 11:00 2017-01-14 11:03 ...
1 2017-01-14 11:10 2017-01-14 11:11 ...
1 2017-01-14 11:20 2017-01-14 11:24 ...
A new group must me created when we have a gap of 5 or X minutes or more between current row datetime value and next row datetime value.
I have this kind of query, but I can't figure out where to group rows when it have a gap of 5 minutes or more.
WITH groups(DateTimeField, grp) AS
(
SELECT DISTINCT
DateTimeField,
DATEDIFF(MINUTE, DateTimeField, lag(DateTimeField) OVER (ORDER BY DateTimeField DESC)) grp
FROM
MyTable
WHERE
ID = 1
)
SELECT
COUNT(*) AS consecutiveDates,
MIN(DateTimeField) AS minDate,
MAX(DateTimeField) AS maxDate
FROM
groups
GROUP BY
grp
ORDER BY
1 DESC, 2 DESC
Best regards,