Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the sum of minutes in overlapping timeranges

I need to calculate the sum of minutes of terms. Overlapping terms should not count multiple times.

Declare @Terms table (Start DATETIME, Finish DATETIME)
INSERT INTO @Terms values
    ('2016-8-3 08:00','2016-8-3 09:00'),
    ('2016-8-3 09:00','2016-8-3 10:00'),
    ('2016-8-3 08:00','2016-8-3 09:30'),   -- overlapping term
    ('2016-8-3 11:00','2016-8-3 12:00')

The result from the data above should be 180 minutes (3 hours). What is the easiest and fastest way to to this?

like image 982
brenkdar Avatar asked Aug 03 '16 15:08

brenkdar


People also ask

How do you calculate overlapping time?

Overlap = min(A2, B2) - max(A1, B1) + 1. In other words, the overlap of two integer intervals is a difference between the minimum value of the two upper boundaries and the maximum value of the two lower boundaries, plus 1.

What does time overlap mean?

Time zone overlap means that two or more time zones intersect each other. In the context of working remotely, this means that people in two different time zones can theoretically be working at the same time. For instance, Uruguay is two hours ahead of U.S. time depending on where you live.

How do you find overlapping time intervals in SQL?

Overlapping Time Periods Characteristics Basically, a period can be represented by a line fragment on time axis which has two boundaries; starttime and endtime. To claim two time periods to be overlapping, they must have common datetime values which is between lower and upper limits of both periods.


1 Answers

With the help of a cross apply.

Declare @Terms table (Start DATETIME, Finish DATETIME)
INSERT INTO @Terms values
    ('2016-8-3 08:00','2016-8-3 09:00'),
    ('2016-8-3 09:00','2016-8-3 10:00'),
    ('2016-8-3 08:00','2016-8-3 09:30'),   -- overlapping term
    ('2016-8-3 11:00','2016-8-3 12:00')

Select Minutes = sum(Minutes)
 From (
        Select Distinct 
               B.DateR1
              ,B.DateR2
              ,Minutes = DateDiff(Minute,B.DateR1,B.DateR2)
         From @Terms A
         Cross Apply (
                      Select DateR1=Min(Start)
                            ,DateR2=max(Finish) 
                       From  @Terms 
                       Where Start <= A.Finish and Finish >= A.Start
                     ) B
 ) A

Returns

Minutes
180

The sub-query returns

DateR1                     DateR2                   Minutes
2016-08-03 08:00:00.000    2016-08-03 10:00:00.000  120
2016-08-03 11:00:00.000    2016-08-03 12:00:00.000  60
like image 110
John Cappelletti Avatar answered Sep 21 '22 05:09

John Cappelletti