MySQL difference between two rows of a SELECT Statement

后端 未结 5 1041
执笔经年
执笔经年 2020-11-27 20:53

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

5条回答
  •  情深已故
    2020-11-27 21:58

    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.

提交回复
热议问题