Sum amount of overlapping datetime ranges in MySQL

后端 未结 3 1639
北恋
北恋 2020-12-30 17:55

I have a table of events, each with a StartTime and EndTime (as type DateTime) in a MySQL Table.

I\'m trying to output the sum of overlapping times

3条回答
  •  甜味超标
    2020-12-30 18:02

    Try this:

    SELECT `COUNT`, SEC_TO_TIME(SUM(Duration))
    FROM (
        SELECT
            COUNT(*) AS `Count`,
            UNIX_TIMESTAMP(Times2.Time) - UNIX_TIMESTAMP(Times1.Time) AS Duration
        FROM (
            SELECT @rownum1 := @rownum1 + 1 AS rownum, `Time`
            FROM (
                SELECT DISTINCT(StartTime) AS `Time` FROM events
                UNION
                SELECT DISTINCT(EndTime) AS `Time` FROM events
            ) AS AllTimes, (SELECT @rownum1 := 0) AS Rownum
            ORDER BY `Time` DESC
        ) As Times1
        JOIN (
            SELECT @rownum2 := @rownum2 + 1 AS rownum, `Time`
            FROM (
                SELECT DISTINCT(StartTime) AS `Time` FROM events
                UNION
                SELECT DISTINCT(EndTime) AS `Time` FROM events
            ) AS AllTimes, (SELECT @rownum2 := 0) AS Rownum
            ORDER BY `Time` DESC
        ) As Times2
        ON Times1.rownum = Times2.rownum + 1
        JOIN events ON Times1.Time >= events.StartTime AND Times2.Time <= events.EndTime
        GROUP BY Times1.rownum
    ) Totals
    GROUP BY `Count`
    

    Result:

    1, 03:00:00
    2, 02:00:00
    3, 02:00:00
    

    If this doesn't do what you want, or you want some explanation, please let me know. It could be made faster by storing the repeated subquery AllTimes in a temporary table, but hopefully it runs fast enough as it is.

提交回复
热议问题