I am trying to make the difference of two rows in an mysql database.
I have this table containing ID, kilometers, date, car_id, car_driver etc...
Since I don\'t alwa
With data unsorted I can only think of inline subquery (not a good idea on the large table):
select t1.*,
t1.Kilometers - (select top 1 kilometers from mytable t2 where t2.date < t1.date order by t2.date desc) as number_km_since_last_date
from mytable t1
If you get data sorted you can use left join
select t1.*
t1.Kilometers - t2.Kilometers as number_km_since_last_date
from mytable t1
left join mytable t2
on t1.id = t2.id + 1
You can probably tell that I'm more of a TSQL guy so you might need to adjust syntax for MySQL.