从两个表中查询数据+一个表只能使用最新数据进行查询

时间:2013-05-07 18:31:15

标签: sql sql-server sql-server-2005

好吧,我有一个我正在查询的表,其中包含每分钟左右更新的历史数据。我使用以下内容从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的地方,只有最近的结果......

2 个答案:

答案 0 :(得分:1)

您只需将另一个JOIN添加到您拥有的现有查询中即可。当在ON子句中使用显式(INNER)JOIN匹配键时,与在WHERE子句中过滤的推断CROSS 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

答案 1 :(得分: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