简体   繁体   English

如何在MySQL中计算当前行与上一行之间的时差

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

I have mysql table t1 like this : 我有这样的mysql表t1:

“ t1表”根据先前的查询临时创建的表

What i want to do is do calculations between all rows and save the value in new coloumn called diff 我想做的是在所有行之间进行计算,并将值保存在称为diff的新列中

TICKETID| DATENEW  | DIFF
16743     12:36:46   0
16744     12:51:25   15.  minute  
16745     12:57:25   6.5  minute
..........
.......
etc

i know there are similar questions ,but ive tried all of the solutions posted here with no success,so how to solve this query ??? 我知道也有类似的问题,但是我尝试了所有在此发布的解决方案均未成功,因此如何解决此查询?

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: 要获取当前行和上一行之间的时间差(分钟),可以在datenow和上一时间使用timestampdiff ,这可以通过子查询获得:

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: 这是使用变量存储可能更快的先前datenew值的另一种方法:

select ticketid, datenew, timestampdiff(minute,datenew,prevdatenew)
from (
    select ticketid, datenew, @prevDateNew as prevdatenew, 
      @prevDateNew := datenew
    from mytable order by ticketid
) t1
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. 注意:这假设表中没有缺失的ID。 You might have to change the join condition if there were missing id's. 如果缺少ID,则可能必须更改join条件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM