我正在尝试为游标建立选择语句。
我的桌子上有车辆事件,对于我的光标,我正在确定的时间段内抓取所有点火和熄火事件。
我想通过联盟将每辆车在该时间段内的第一个和最后一个事件合并到我的选择中,我的想法是,其中的where子句应该是该事件不能打开或关闭,因此不会重复本身。但是我不知道每辆车如何举办赛事。
我目前拥有的是以下物品。
SELECT
al.ActivityLogID,
al.[VehicleID],
al.[DriverID],
al.[ActivityDateTime],
al.[EventSubTypeId]
FROM
[activitylog] a
WHERE
[ActivityDateTime] BETWEEN @StartDateTime AND @EndDateTime AND
[EventSubTypeID] = 3 -- ignitionON
UNION
SELECT
al.ActivityLogID,
al.[VehicleID],
al.[DriverID],
al.[ActivityDateTime],
al.[EventSubTypeId]
FROM
[activitylog] a
WHERE
[ActivityDateTime] BETWEEN @StartDateTime AND @EndDateTime AND
[EventSubTypeID] = 4 -- ignitionOFF
ORDER BY
[VehicleID], [ActivityDateTime]
答案 0 :(得分:0)
假设IgnitionOFF在IgnitionON日期时间之后
SELECT al.[VehicleID]
, al.[DriverID]
, MIN(al.[ActivityDateTime])
, MAX(al.[ActivityDateTime])
FROM [activitylog] al
WHERE [ActivityDateTime] BETWEEN @StartDateTime AND @EndDateTime AND
[EventSubTypeID] IN (3,4) -- ignitionON/OFF
GROUP BY al.[VehicleID]
, al.[DriverID]
ORDER BY al.[VehicleID]
, al.[DriverID]
或者您可能需要这个:
SELECT [VehicleID]
,[EventSubTypeID]
,[ActivityDateTime]
FROM
(
SELECT al.[VehicleID]
, [EventSubTypeID]
, MIN(al.[ActivityDateTime]) AS "ActivityDateTime"
FROM [activitylog] al
WHERE [ActivityDateTime] BETWEEN @StartDateTime AND @EndDateTime AND
[EventSubTypeID] = 3 -- ignitionON
GROUP BY al.[VehicleID], [EventSubTypeID]
UNION
SELECT al.[VehicleID]
, [EventSubTypeID]
, MAX(al.[ActivityDateTime]) AS "ActivityDateTime"
FROM [activitylog] al
WHERE [ActivityDateTime] BETWEEN @StartDateTime AND @EndDateTime AND
[EventSubTypeID] = 4 -- ignitionOFF
GROUP BY al.[VehicleID], [EventSubTypeID]
)
ORDER BY [VehicleID], [EventSubTypeID]