2

这是我的桌子

VehicleName EventDate       Message  Landmark
071-314     28-Sep-12 5pm   On Duty 
071-314     28-Sep-12 6pm   Driving 
071-314     28-Sep-12 7pm   On Duty 
071-314     28-Sep-12 8pm   Driving 
071-314     28-Sep-12 3am   Off Duty    
071-315     28-Sep-12 4am   Driving 
071-315     28-Sep-12 5am   On Duty 
071-315     28-Sep-12 6am   Driving 
071-315     28-Sep-12 7am   On Duty 
071-315     28-Sep-12       Off Duty    

我需要做的是找到从“上班”到下一个“驾驶”或“下班”状态的区别。它也需要由车辆名称分隔。

这可以通过访问吗?

4

1 回答 1

1

我将您的样本数据放入名为 [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

那是你要找的吗?

于 2013-04-16T23:14:17.903 回答