How to calculate time difference between current and previous row in MySQL

后端 未结 2 868
心在旅途
心在旅途 2021-01-26 16:58

I have mysql table t1 like this :

What i want to do is do calculations between all rows and save the value in new coloumn called diff

TICKETID         


        
相关标签:
2条回答
  • 2021-01-26 17:26
    select 
     t1.*
    ,coalesce(timestampdiff(MINUTE,t2.dt,t1.dt),0) as tdiff 
    from t t1 left join t t2
    on t1.id = t2.id+1
    order by t1.id
    

    As you are only looking for a difference between the current row and the next, you can join on the next row and calculate the time difference in minutes.

    Note: This assumes there are no missing id's in the table. You might have to change the join condition if there were missing id's.

    SQL Fiddle: http://www.sqlfiddle.com/#!9/4dcae/15

    0 讨论(0)
  • 2021-01-26 17:40

    To get the time difference in minutes between the current and previous row, you can use timestampdiff on datenow and the previous time, which you can get via subquery:

    select ticketid, datenew,
        timestampdiff(minute,datenew,(select datenew from mytable t2
            where t2.ticketid < t1.ticketid order by t2.ticketid desc limit 1)) as diff
    from mytable t1
    

    Update

    Here's another way using a variable to store the previous datenew value that might be faster:

    select ticketid, datenew, timestampdiff(minute,datenew,prevdatenew)
    from (
        select ticketid, datenew, @prevDateNew as prevdatenew, 
          @prevDateNew := datenew
        from mytable order by ticketid
    ) t1
    
    0 讨论(0)
提交回复
热议问题