Skip to content
Advertisement

SQL – Combine two rows if difference is below threshhold

I have a table like this in SQL Server:

What I would like to have is a query that outputs consolidated records based on the time difference between two consecutive records (end_time of row n and start_time row n+1) . All records where the time difference is less than 2 minutes should be combined into one time entry and the ID of the first record should be kept. This should also combine more than two records if multiple consecutive records have a time difference less than 2 minutes.

This would be the expected output:

Thanks in advance for any tips how to build the query.

Edit: I started with following code to calculate the lead_time and the time difference but do not know how to group and consolidate.

Advertisement

Answer

The window function in t-sql can realize a lot of data statistics, such as

In order to better describe the process of data construction, I simply use c0, c1, c2… to represent levels, you can merge some levels and optimize. If you can’t use id as a sorting condition, then you need to change the sorting part in the above statement.

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