Skip to content
Advertisement

Calculate overlap time in seconds for groups in SQL

I have a bunch of timestamps grouped by ID and type in the sample data shown below.

I would like to find overlapped time between start_time and end_time columns in seconds for each group of ID and between each lead and follower combinations. I would like to show the overlap time only for the first record of each group which will always be the “lead” type.

For example, for the ID 1, the follower’s start and end times in row 3 overlap with the lead’s in row 1 for 193 seconds (from 09:00:00 to 09:03:13). the follower’s times in row 3 also overlap with the lead’s in row 2 for 133 seconds (09:01:00 to 2020-05-07 09:03:13). That’s a total of 326 seconds (193+133)

I used the partition clause to rank rows by ID and type and order them by start_time as a start.

How do I get the overlap column?

Advertisement

Answer

Tried this a couple of way and got it to work.

I first joined 2 tables with individual records for each type, ‘lead’ and ‘follower’ and created a case statement to calculate max start time for each lead and follower start time combination and min end time for each lead and follower end time combination. Stored this in a temp table.

Then created an outer query to lookup the temp table just created to find the difference between start time and end time for each lead and follower combination in seconds

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