我有2个相当简单的查询,我需要制作一个。我今天只是心理上的空白。
SELECT max(StatusReportID)
FROM dbo_VehicleStatusReport
和
SELECT StatusReportID, StatusReportTime, CarNumber, VehicleID,
DriverNumber, DriverID, VehicleStatus, LocationX, LocationY,
Speed, Direction, InvalidGPS
FROM dbo_VehicleStatusReport
WHERE StatusReportID > " & MaxStatusReportID2 & "
其中& MaxStatusReportID2&是第一个查询减去3000(-3000)
的结果答案 0 :(得分:4)
将它包装在子查询上,
SELECT StatusReportID,
StatusReportTime,
CarNumber,
VehicleID,
DriverNumber,
DriverID,
VehicleStatus,
LocationX,
LocationY,
Speed,
Direction,
InvalidGPS
FROM dbo_VehicleStatusReport
WHERE StatusReportID >
((SELECT max(StatusReportID) FROM dbo_VehicleStatusReport) - 3000)
答案 1 :(得分:3)
;WITH x AS
(
SELECT MaxSRID = MAX(StatusReportID) - 3000
FROM dbo_VehicleStatusReport
)
SELECT v.StatusReportID, v.StatusReportTime, ...
FROM dbo_VehicleStatusReport AS v
INNER JOIN x
ON v.StatusReportID > x.MaxSRID;
如果目标是找到最新的2999条目,那么以下内容更简单,更可靠:
SELECT TOP (2999) StatusReportID, StatusReportTime, ...
FROM dbo_VehicleStatusReport
ORDER BY StatusReportTime DESC;
这是因为:
IDENTITY
值可能会因删除和回滚而丢失,因此依赖MAX - 3000
的查询可能不一定会产生2999行。IDENTITY
列可以重新种植,并且可以覆盖值,因此假设增加值意味着以后可能会有问题。