需要帮助查找访问中的下一条记录

时间:2013-04-16 18:33:48

标签: sql ms-access

这是我的表

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    

我需要做的是找到“值班”与下一次“驾驶”或“休假”状态的区别。它也需要与车辆名称分开。

这可以通过访问吗?

1 个答案:

答案 0 :(得分:1)

我将您的样本数据放入名为[DutyEvents]的表中,并将其调整为一致(例如,第一个[VehicleName]的最终“Off Duty”是在第二天凌晨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

...然后我创建了以下Access查询...

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

那是你在找什么?

相关问题