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

后端 未结 2 869
心在旅途
心在旅途 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: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
    

提交回复
热议问题