Skip to content
Advertisement

Consolidate records in T-SQL where the difference between end time of the current record and start time of the next record is less than x minutes

I want to consolidate records based on a time gap of 5 minutes between the current row-end date and the next row start date. How can I achieve this T-SQL?

Before Consolidation, the table is like below –

It should look like below after consolidation –

Advertisement

Answer

This is a type of gaps-and-islands problem. For this problem, use lag() and a cumulative sum:

The lag() gets the previous endtime for comparison. The middle query determines when a new “island” starts. This occurs when there is more than 5 minutes between the previous endtime and current starttime. The outer query then aggregates to get the final result.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement