两个表中的SQL MAX查询查找

时间:2014-09-26 06:27:36

标签: sql sql-server

尝试从SQL Server返回MAX值时,我有一些乐趣:

SELECT 
    MAX(GPSdata_1.Longitude) AS Expr1, 
    MAX(GPSdata_1.Latitude) AS Expr2, 
    CAST(MAX(GPSdata_1.Speed) AS DECIMAL(9 , 0)) AS Expr3, 
    MAX(GPSdata_1.Date) AS Time, Units.FleetName 
FROM 
    GPSdata AS GPSdata_1 
INNER JOIN 
    Units ON GPSdata_1.UnitID = Units.IMEInumber 
GROUP BY 
    Units.FleetName

问题由于某些原因,Long和Lat没有返回正确的值

我试过了

select *
from mytable t1
inner join
  (
 select max(ID) 
from mytable
group by UnitID
) t2
 on t1.ID = t2.ID

基本上我有1个表中有ID,我想返回ID的最后/最大记录。

1 个答案:

答案 0 :(得分:0)

我最终使用以下命令

  SELECT TT.Longitude,TT.Latitude,TT.Date,CAST(TT.Speed AS DECIMAL(9, 0)) 
  AS Expr1,Units.FriendlyName
  FROM GPSdata AS TT 
  INNER JOIN (SELECT UnitID, MAX(Date) AS date1
              FROM GPSdata
              GROUP BY UnitID) AS T2 ON TT.UnitID = T2.UnitID 
                                     AND TT.Date = T2.date1 
  INNER JOIN Units ON TT.UnitID = Units.IMEInumber
  GROUP BY TT.Date,TT.Longitude,TT.Latitude,Units.FriendlyName,
  CAST(TT.Speed AS DECIMAL(9, 0))