mysql时间段重叠,MySQL中重叠日期时间范围的总和

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 and the number of events that overlapped.

What is the most efficient / simple way to perform this query in MySQL?

CREATE TABLE IF NOT EXISTS `events` (

`EventID` int(10) unsigned NOT NULL auto_increment,

`StartTime` datetime NOT NULL,

`EndTime` datetime default NULL,

PRIMARY KEY (`EventID`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;

INSERT INTO `events` (`EventID`, `StartTime`, `EndTime`) VALUES

(10001, '2009-02-09 03:00:00', '2009-02-09 10:00:00'),

(10002, '2009-02-09 05:00:00', '2009-02-09 09:00:00'),

(10003, '2009-02-09 07:00:00', '2009-02-09 09:00:00');

# if the query was run using the data above,

# the table below would be the desired output

# Number of Overlapped Events | Total Amount of Time those events overlapped.

1, 03:00:00

2, 02:00:00

3, 02:00:00

The purpose of these results is to generate a bill for hours used. (if you have one event running, you might pay 10 dollars per hour. But if two events are running, you only have to pay 8 dollars per hour, but only for the period of time you had two events running.)

解决方案

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.

你可能感兴趣的:(mysql时间段重叠)