MySql:最近行之间的时间差

时间:2017-04-05 13:06:20

标签: mysql time difference

我有这个问题,我有表XYZ这些值:

product_id,user_name,event_type,event_time

ABCD123,user1,REPAIR,2017-01-16 14:51:28

ABCD123,user1,REPAIR DONE,2017-01-16 15:51:28

ABCD123,user1,REPAIR,2017-01-16 16:51:28

ABCD123,user1,REPAIR DONE,2017-01-16 18:51:28

如何才能获得第一次REPAIR DONE和第一次REPAIR以及第二次REPAIR DONE和第二次REPAIR之间的时差? 我试过这个:

select a.product_id, a.user_name, b.event_time as start_time, a.event_time as end_time,  FORMAT((TIMESTAMPDIFF(SECOND, b.event_time, a.event_time)/3600),2) as difference   
FROM XYZ a  
join XYZ b
ON  a.product_id = b.product_id and a.user_name = b.user_name and a.event_type = 'REPAIR DONE' and b.event_type = 'REPAIR'
group by a.product_id, a.user_name 
order by a.event_time asc

但由于某种原因,结果如下:

ABCD123,user1,差异1小时

ABCD123,user1,差异4小时

正确的是:

ABCD123,user1,差异1小时

ABCD123,user1,差异2 HOURS

换句话说,在第二行,我得到第一个REPAIR和第二个REPAIR DONE之间的差异的结果,而不是第二个REPAIR和第二个REPAIR DONE。

请问有人给我一些建议吗?

2 个答案:

答案 0 :(得分:0)

你可以使用像这样的查询_

    SELECT x1.products_id,
     x1.user_name, 
     CONCAT( 'difference ', HOUR(x2.event_time - x1.event_time),' Hour')
    FROM xyz x1
    LEFT JOIN xyz x2 ON x1.event_time < x2.event_time AND x2.event_type = 'REPAIR DONE'
    WHERE x1.event_type = 'REPAIR'
    ORDER BY x1.event_time;

答案 1 :(得分:0)

尝试此查询

select r.*, ROUND((TIMESTAMPDIFF(HOUR,r.event_time,rd.event_time))) as time_t
from ( (select * from xyz where event_event_type='REPAIR') as r 
JOIN (select * from xyz where event_type='REPAIR DONE') as rd 
ON(rd.event_time >r.event_time ) ) group by 
r.product_id,r.user_name,r.event_type,r.event_time having MIN(rd.event_time)

根据我的理解,它显示了正确的输出。因为你的问题看起来很有趣,这就是为什么我试一试,虽然我很确定我提供的解决方案并不是很好的性能。但是第一次尝试这是输出,你可以仔细考虑它,可以使整个查询表现更好。