2017-04-05 74 views
1

我有这个问题,我有表XYZ这些值之间的次数差:MySQL的:最接近行

的product_id,USER_NAME,EVENT_TYPE,EVENT_TIME

ABCD123,用户1,REPAIR,2017年1月16日14点51分28秒

ABCD123,用户1,REPAIR DONE,2017年1月16日15时51分28秒

ABCD123,用户1,修理,2017年1月16日16时51分二十八秒

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

怎样才能获得第一次维修完成和第一次维修和第二次维修完成和第二次维修之间的时间差? 我尝试这样做:

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,用户1,差异1小时

ABCD123,用户1,差4小时

正确的是:

ABCD123,用户1,差1小时

ABCD123,用户1,差2小时

换句话说,在第二行我得到第一修复和DONE DONE代替第二修复和第二修复第二修复之间的差的结果。

有人可以给我一些建议吗?

回答

0

您可以使用查询像THIS_

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; 
+0

我很抱歉,我无法让您的解决方案正常工作,但可能是我的问题。 – Raymond

+0

你可以在http://sqlfiddle.com/上发布一些表格,我会检查它 –

+0

你好,我通过电子邮件向你发送了样本数据,sqlfiddle对我来说似乎对第一次看起来有点困惑。对不起。谢谢你的尝试。 – Raymond

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) 

它显示了正确的输出按我的理解。由于你的问题对我来说很有意思,所以我试了一下,但我确信我提供的解决方案并不是很好,但根据性能不同,只是第一次尝试这是输出,你可以考虑它,可以使整个查询执行得更好。

+0

非常感谢,Abhisek!你的解决方案确实有效在所有记录的表格中,我遇到了一些重复的问题,但是我会尽力解决。 – Raymond

+0

对不起,这当然是我的错。有了所有的记录,我必须改变ON的原因(rd.event_time> r.event_time和r.product_id = rd.product_id) – Raymond

+0

@Raymond所以你的意思是我的答案是你的问题的解决方案 –