How can I use SQL to find events with overlapping durations?

62 Views Asked by At

I have the following table

Field Type Null Key
EventId int(11) NO PRI
Duration int(11) NO
EventParentId int(11) NO MUL
EventDateTime datetime NO PRI
Created datetime NO
est_datetime datetime YES MUL
pacific_ts int(11) YES MUL
eastern_ts int(11) YES MUL
updated datetime YES

Edit: I need to find all of the unique EventParentId of any column that would have an overlap. eastern_ts and pacific_ts would be the start time and each event also has a duration in seconds. I am newer to SQL and not sure how this would need to be done. Would it be easier to just grab all columns and filter using Java or is this possible with only SQL?

EventId Duration EventParentId EventDateTime pacific_ts eastern_ts
1234 30 56789 2023-03-01T10:00:00 1677693600 1677704400
1235 45 98765 2023-03-01T10:01:00 167769366 NULL
1236 45 98765 2023-03-01T10:01:15 1677693675 NULL
4567 60 34567 2023-03-03T09:45:20 NULL 1677865520
4568 45 34567 2023-03-03T09:45:40 NULL 1677865540
2345 60 65432 2023-03-03T09:45:40 1677854740 1677865540

Because 1235 and 1236 share an EventParentId and have overlapping duration I would expect EventParentId 98765. I would also expect EventParentId 34567 because 4567 and 4568 have overlapping durations, but would not expect 65432 because it does not overlap anything within the same EventParentId

Edit: Expected result

EventId Duration EventParentId EventDateTime pacific_ts eastern_ts
1235 45 98765 2023-03-01T10:01:00 167769366 NULL
4567 60 34567 2023-03-03T09:45:20 NULL 1677865520
1

There are 1 best solutions below

0
MatBailie On
SELECT
  *
FROM
  your_table  AS a
WHERE
  EXISTS (
    SELECT *
      FROM your_table   AS b
     WHERE b.EventParentId  = a.EventParentId
       AND b.EventID       <> a.EventID
       AND b.EventDateTime >= a.EventDateTime
       AND b.EventDateTime <  a.EventDateTime + INTERVAL a.Duration SECOND
  )