MRogo
MRogo

Reputation: 55

MySQL how to get a sum of start/end dates with possible overlapping dates

I have a table of start/end dates that I want to group by id and sum the total time for each id. For example:

fk_id            start              end
3                2014-03-21 10:02   2014-05-01 08:05
3                2014-06-05 05:00   2014-06-20 22:00  
5                2014-03-10 08:00   2014-06-20 13:50  
5                2014-05-10 09:45   2014-06-22 15:31

For fk_id=3 there is no problem:

But for fk_id=5 the dates overlap:

Is there any way to do this type of query in MySQL?

Thanks!

Upvotes: 2

Views: 89

Answers (1)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48187

Use variable to fix the ranges before agregate the totals

SQL DEMO

SELECT t.`fk_id`,
       @rn := if(@id = `fk_id`, 
                 @rn + 1, 
                 if(@id:=`fk_id`, if(@end:='1900-01-01 00:00:00',1,1), if(@end:='1900-01-01 00:00:00',1,1))   
                ) as rn,
       if(start < @end, 
          @end, 
          if(@end := end, `start`, `start`) 
         ) as `start`, 
       end
FROM Table1 t
CROSS JOIN (SELECT @id := 0, @end := STR_TO_DATE('1900-01-01 00:00:00', '%Y-%m-%d %H:%i:%s') as e, @rn := 0) t
ORDER BY `fk_id`, `start`

OUTPUT

enter image description here

Upvotes: 1

Related Questions