Optimal performing query for latest record for each N

前端 未结 3 1435
慢半拍i
慢半拍i 2020-12-31 05:23

Here is the scenario I find myself in.

I have a reasonably big table that I need to query the latest records from. Here is the create for the essential columns for t

3条回答
  •  耶瑟儿~
    2020-12-31 05:27

    Depends on your data (how many rows are there per group?) and your indexes.

    See Optimizing TOP N Per Group Queries for some performance comparisons of 3 approaches.

    In your case with millions of rows for only a small number of Vehicles I would add an index on VehicleID, Timestamp and do

    SELECT CA.*
    FROM   Vehicles V
           CROSS APPLY (SELECT TOP 1 *
                        FROM   ChannelValue CV
                        WHERE  CV.VehicleID = V.VehicleID
                        ORDER  BY TimeStamp DESC) CA  
    

提交回复
热议问题