Skip to content
Advertisement

Merge several rows into one if they have a gap less than a 5 seconds

I’m trying to find a SQL query that lets me to merge some rows into one from a table that have a gap less than 5 seconds. For example, I have a table like the following:

So, I want to have a result like this:

For John there are two rows that have a gap less than 5 seconds, so they will merge in one row for the same day. The same happens with Walt.

Can I do this with a SQL query?

Thank you in advance.

Advertisement

Answer

You just need to check if the next date is within 5 seconds after the current row and if so – remove such a row. This can be achieved with LEAD analytical function.

name   | dt_date   
:----- | :---------
John   | 2021-02-01
John   | 2021-02-01
John   | 2021-02-07
Joseph | 2021-01-23
Walt   | 2021-01-04
Walt   | 2021-01-14

db<>fiddle here

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