Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Soma de intervalos de data e hora sobrepostos no MySQL

SELECT
  COUNT(*) as occurrence
  , sub.event_id
  , SEC_TO_TIME(SUM(LEAST(e1end, e2end) - GREATEST(e1start, e2start)))) as duration
FROM
  (  SELECT  
      , e1.event_id
      , UNIX_TIMESTAMP(e1.starttime) as e1start
      , UNIX_TIMESTAMP(e1.endtime) as e1end
      , UNIX_TIMESTAMP(e2.starttime) as e2start
      , UNIX_TIMESTAMP(e2.endtime) as e2end
    FROM events e1
    INNER JOIN events e2 
      ON (e1.eventtype = e2.eventtype AND e1.id <> e2.id
      AND NOT(e1.starttime > e2.endtime OR e1.endtime < e2.starttime))
  ) sub
GROUP BY sub.event_id 
ORDER BY occurrence DESC