我有这个问题,我有具有这些值的表 XYZ:
product_id, user_name, event_type, event_time
ABCD123,user1,修复,2017-01-16 14:51:28
ABCD123,user1,修复完成,2017-01-16 15:51:28
ABCD123,user1,修复,2017-01-16 16:51:28
ABCD123,user1,修复完成,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 小时
换句话说,在第二行中,我得到的是第一次修复和第二次修复完成之间的差异结果,而不是第二次修复和第二次修复完成之间的差异。
有人可以给我一些建议吗?
最佳答案
您可以使用这样的查询_
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;
关于MySql:最近的行之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232160/