在何处获取每个ID的前1行

时间:2019-09-11 09:36:44

标签: sql-server tsql query-performance where-in

我有一个表格,我想获取其中每个参数的最新条目

select GpsData.VehicleId, GpsData.Id, GpsData.DateTime
from GpsData
where GpsData.VehicleId in (44, 1054, 1055, 31, 22, 1058)
order by GpsData.VehicleId desc;

2 个答案:

答案 0 :(得分:2)

使用NOT EXISTS

select g.VehicleId, g.Id, g.DateTime
from GpsData g
where g.VehicleId in (44, 1054, 1055, 31, 22, 1058)
and not exists (
  select 1 from GpsData
  where VehicleId = g.VehicleId and DateTime > g.DateTime 
)
order by g.VehicleId desc;

或带有row_number()窗口功能:

select t.VehicleId, t.Id, t.DateTime
from (
  select VehicleId, Id, DateTime,
    row_number() over (partition by VehicleId order by DateTime desc) as rn   
  from GpsData 
  where VehicleId in (44, 1054, 1055, 31, 22, 1058)
) as t
where t.rn = 1
order by t.VehicleId desc;

答案 1 :(得分:1)

您可以使用TOP 1 WITH TIES

SELECT TOP 1 WITH TIES
    VehicleId, 
    Id, 
    [DateTime]
FROM GpsData
WHERE VehicleId in (44, 1054, 1055, 31, 22, 1058)
ORDER BY ROW_NUMBER() OVER (PARTITION BY VehicleId ORDER BY [DateTime] DESC)

我们可以如下使用动态查询:

 DECLARE @Ids NVARCHAR(MAX) = '44, 1054, 1055, 31, 22, 1058', @sql NVARCHAR(3000)

 SET @sql = '
    SELECT TOP 1 WITH TIES VehicleId, 
        Id, 
        [DateTime] 
    FROM GpsData 
    WHERE VehicleId IN (' + @ids + ') 
    ORDER BY ROW_NUMBER() OVER (PARTITION BY VehicleId ORDER BY [DateTime] DESC)'

EXEC(@sql)