2017-04-05 69 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所以你的意思是我的答案是你的問題的解決方案 –