来自分区的最新独特记录

时间:2014-07-14 15:32:21

标签: sql sql-server sql-server-2008

我有一张包含此类信息的表格

VehicleID | dtDate | Lat | long

每隔一段时间使用新的lat和long来创建一条新记录,我试图获得每辆车的最新日期,所以我的lat和long将是最新的。

select row_number over (partition by vehicleID order by dtDate), 
 vehicleID, 
 Lat,
 Long
from database.schema.table

3 个答案:

答案 0 :(得分:0)

如果这只是一个临时查询,我会在这里使用CTE:

WITH CTE1
AS (
    SELECT vehicleID
        ,Lat
        ,Long
        ,row_number OVER (
            PARTITION BY vehicleID ORDER BY dtDate DESC
            ) AS latestdate
    FROM MyTable
    )
SELECT vehicleID
    ,Lat
    ,Long
FROM CTE1
WHERE latestdate = 1

答案 1 :(得分:0)

;WITH   vehicleCTE
AS (SELECT ROW_NUMBER() OVER (PARTITION BY vehicleID ORDER BY dtDate DESC) AS rowNum,
               vehicleID,
               Lat,
               Long,
               dtDate
        FROM   t1)
SELECT vehicleID,
       Lat,
       Long,
       dtDate
FROM   vehicleCTE
WHERE  rowNum = 1;

答案 2 :(得分:0)

如果您想查询查询中的最高记录,可以使用以下查询

WITH cte 
AS
(
select row_number() over 
    (partition by vehicleID order by dtDate DESC) as RowNum
    , vehicleID, Lat,Long
from database.schema.table
)
SELECT * FROM cte
WHERE RowNum=1;