1

我有 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)

4

2 回答 2

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)
于 2013-01-22T01:45:19.527 回答
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;

这是因为:

  1. IDENTITY值可能会因删除和回滚而丢失,因此所依赖的查询MAX - 3000不一定会产生 2999 行。
  2. IDENTITY列可以重新播种并且值可以被覆盖,因此假设值增加意味着稍后可能会出现问题。
于 2013-01-22T01:52:41.717 回答