sql >> Database teknologi >  >> RDS >> Mysql

Summen af ​​overlappende datointervaller i 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



  1. masseopdatering af en liste over værdier fra en liste over id'er

  2. Sådan finder du data fra sidste uge i MySQL

  3. Escape-værdier i Mysqljs

  4. Hvad betyder select count(1) fra table_name på alle databasetabeller?