如何进行2个SQL查询1

时间:2013-01-22 01:43:41

标签: sql sql-server tsql

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

的结果

2 个答案:

答案 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;

这是因为:

  1. IDENTITY值可能会因删除和回滚而丢失,因此依赖MAX - 3000的查询可能不一定会产生2999行。
  2. IDENTITY列可以重新种植,并且可以覆盖值,因此假设增加值意味着以后可能会有问题。