MySql:最近的行之间的时间差

标签 mysql time difference

我有这个问题,我有具有这些值的表 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/

相关文章:

r - 计算 %H 中的时间差 :%M:%S format in R

mysql - 在不使用嵌套查询的情况下使用 GROUP BY 和 ORDER BY 优化 JOINed 表上的 MySQL 查询

php - 在前3个php mysql之后获取一定数量的行

Python Excel 突出显示单元格差异

time - 多元时间序列分类

python - 在 python 中计时时,我应该如何考虑 subprocess.Popen() 开销?

r - 计算列值之间的差异

python - 使用 django 查询从多个表中检索详细信息

php - 我应该将 Unix 时间戳转换为 "hour"时间戳吗?

php - mysql代码中的时间变化