0

好的,我正在查询一个表,其中包含每分钟左右更新的历史数据。我使用以下方法通过 VehicleKey 从中提取最新数据:

SELECT p.VehicleKey, p.Timestamp, p.Latitude, p.Longitude, p.Speed
FROM AVLVehiclePosition p,
    (SELECT max(Timestamp) as maxtime, VehicleKEy
      FROM AVLVehiclePosition
      GROUP BY VehicleKey) maxresults  
WHERE p.VehicleKey = maxresults.VehicleKEy  
AND p.Timestamp = maxresults.maxtime

我还需要从第二个表中提取一些相关信息,并将其与上述查询的结果一起返回。我已经弄清楚如何通过 VehicleKey 为 VehicleKey 的每个实例提取相关数据:

SELECT p.Timestamp, p.Latitude, p.Longitude, p.Speed, v.Name, v.VehicleKey
FROM AVLVehiclePosition p, Vehicle v
WHERE p.VehicleKey = v.VehicleKey

现在我不知道该怎么做才能将这两个查询组合到我将 v.Name 拉到的位置,仅获取最新的结果......

4

2 回答 2

1

您可以简单地将另一个 JOIN 添加到您拥有的现有查询中。与在 WHERE 子句中过滤的推断的 CROSS JOIN(使用逗号分隔的表)相比,当您在 ON 子句中使用显式(INNER)JOIN 匹配键时,它会干净得多:

SELECT p.VehicleKey, p.Timestamp, p.Latitude, p.Longitude, p.Speed, v.Name
FROM AVLVehiclePosition p
JOIN Vehicles v
  ON p.VehicleKey = v.VehicleKey
JOIN (SELECT max(Timestamp) as maxtime, VehicleKEy
      FROM AVLVehiclePosition
      GROUP BY VehicleKey) maxresults  
  ON p.VehicleKey = maxresults.VehicleKEy  
  AND p.Timestamp = maxresults.maxtime

如果你使用 ROW_NUMBER(),你可以让它更干净:

WITH maxResults AS (
  SELECT p.VehicleKey, p.Timestamp, p.Latitude, p.Longitude, p.Speed, v.Name,
         ROW_NUMBER() OVER (PARTITION BY p.VehicleKey ORDER BY p.Timestamp DESC) rowNum
  FROM AVLVehiclePosition p
  JOIN Vehicles v
    ON p.VehicleKey = v.VehicleKey)
SELECT * FROM maxResults
WHERE rowNum = 1
于 2013-05-07T18:37:54.313 回答
0

在两个查询之间使用内连接:

SELECT p.VehicleKey, p.Timestamp, p.Latitude, p.Longitude, p.Speed, v.name
FROM AVLVehiclePosition p
    inner join
    (SELECT max(Timestamp) as maxtime, VehicleKEy
      FROM AVLVehiclePosition
      GROUP BY VehicleKey) as maxresults on p.VehicleKey = maxresults.VehicleKEy and p.Timestamp = maxresults.maxtime
    inner join (
     SELECT name, VehicleKey
     from Vehicle) as v ON maxresults.VehicleKey = v.VehicleKey
于 2013-05-07T18:40:10.657 回答