Hi. I have a SQL table Events (ID int, Event int, StartTime datetime, Duration int
).
Event
is event code (1=system running, 2=break)
Duration
is the amount of seconds that the event was active.
I'd like to get the amount of seconds that event 1 was active, but subtract the duration of event 2.
E.g. event 1 was from 1:00 to 6:00, event 2 from 0:00 to 2:00 and event 2 from 5:00 to 6:00. The total time should be from 2:00 to 5:00 -> 3 hours.
There is a way I can think of: for each event 1 find all events 2 that can intersect with event 1, and for each event 2 in that set: trim its duration to get only the part that was active during its event 1.
e.g. for my event 1 (1:00 - 6:00) I'll find event 2 (0:00 - 2:00), get only the part that interests me (1:00-2:00); find another event 2(5:00-6:00), get the part that interests me (it's whole event 5:00-6:00) - that summed up are two hours. The total time of event 1 was 5 hours; 5 hrs - 2 hrs (event 2) is 3 hours.
But this won't work if there are thousands of events in the specified time frame, so I'd prefer a hint of solution without loops (cursors).