Sum amount of overlapping datetime ranges in MySQL

后端 未结 3 1659
北恋
北恋 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:14

    Start with a table that contains a single datetime field as its primary key, and populate that table with every time value you're interested in. A leap years has 527040 minutes (31622400 seconds), so this table might get big if your events span several years.

    Now join against this table doing something like

    SELECT i.dt as instant, count(*) as events
    FROM instant i JOIN event e ON i.dt BETWEEN e.start AND e.end
    GROUP BY i.dt
    WHERE i.dt BETWEEN ? AND ?
    

    Having an index on instant.dt may let you forgo an ORDER BY.

    If events are added infrequently, this may be something you want to precalculate by running the query offline, populating a separate table.

提交回复
热议问题