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
Solution 1:
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;
Post a Comment for "Mysql Query Get The Last N Rows Per Group"