nikosdi
nikosdi

Reputation: 2158

MySQL Query get the last N rows per Group

Suppose that I have a database which contains the following columns:

VehicleID|timestamp|lat|lon|

I may have multiple times the same VehicleId but with a different timestamp. Thus VehicleId,Timestamp is the primary key.

Now I would like to have as a result the last N measurements per VehicleId or the first N measurements per vehicleId.

How I am able to list the last N tuples according to an ordering column (e.g. in our case timestamp) per VehicleId?

Example:

|VehicleId|Timestamp|
         1|1
         1|2
         1|3
         2|1
         2|2
         2|3
         5|5
         5|6
         5|7

Upvotes: 1

Views: 1011

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

In MySQL, this is most easily done using variables:

select t.*
from (select t.*,
             (@rn := if(@v = vehicle, @rn + 1,
                        if(@v := vehicle, 1, 1)
                       )
             ) as rn
      from table t cross join
           (select @v := -1, @rn := 0) params
      order by VehicleId, timestamp desc
     ) t
where rn <= 3;

Upvotes: 4

Related Questions