通过 Where in 获取每个 Id 的前 1 行

Get top 1 row of each Id by Where in

我有一个 table,我想在

中获取每个参数的最新条目
select GpsData.VehicleId, GpsData.Id, GpsData.DateTime
from GpsData
where GpsData.VehicleId in (44, 1054, 1055, 31, 22, 1058)
order by GpsData.VehicleId desc;

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() window 函数:

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;

您可以使用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)