我将您的样本数据放入名为 [DutyEvents] 的表中,并对其进行了调整以使其保持一致(例如,第一个 [VehicleName] 的最终“下班时间”是在第二天凌晨 3 点)...
VehicleName EventDate Message
----------- ------------------- -------
071-314 2012-09-28 17:00:00 On Duty
071-314 2012-09-28 18:00:00 Driving
071-314 2012-09-28 19:00:00 On Duty
071-314 2012-09-28 20:00:00 Driving
071-314 2012-09-29 03:00:00 Off Duty
071-315 2012-09-28 04:00:00 Driving
071-315 2012-09-28 05:00:00 On Duty
071-315 2012-09-28 06:00:00 Driving
071-315 2012-09-28 07:00:00 On Duty
071-315 2012-09-28 09:00:00 Off Duty
...然后我创建了以下访问查询...
SELECT VehicleName, Message, EventDate AS Start, NextEventDate as End,
Round((NextEventDate - EventDate) * 24, 0) AS Hours
FROM
(
SELECT de.VehicleName, de.EventDate, de.Message,
(SELECT TOP 1 EventDate FROM DutyEvents
WHERE VehicleName = de.VehicleName
AND EventDate > de.EventDate ORDER BY EventDate
) AS NextEventDate
FROM DutyEvents de
WHERE de.Message <> "Off Duty"
)
...产生以下结果...
VehicleName Message Start End Hours
----------- ------- ------------------- ------------------- -----
071-314 On Duty 2012-09-28 17:00:00 2012-09-28 18:00:00 1
071-314 Driving 2012-09-28 18:00:00 2012-09-28 19:00:00 1
071-314 On Duty 2012-09-28 19:00:00 2012-09-28 20:00:00 1
071-314 Driving 2012-09-28 20:00:00 2012-09-29 03:00:00 7
071-315 Driving 2012-09-28 04:00:00 2012-09-28 05:00:00 1
071-315 On Duty 2012-09-28 05:00:00 2012-09-28 06:00:00 1
071-315 Driving 2012-09-28 06:00:00 2012-09-28 07:00:00 1
071-315 On Duty 2012-09-28 07:00:00 2012-09-28 09:00:00 2
那是你要找的吗?