2012-03-15 59 views
1

我有一個表計數時間差異基於狀態

ID | Date  | Time  | Status 
73937 | 3/1/2012 | 17:25:00 | Pending  |  
73938 | 3/1/2012 | 17:27:00 | Pending  | time diff 2 min 
73948 | 3/1/2012 | 17:29:00 | Pending  | time diff 2 min 
73952 | 3/1/2012 | 17:45:00 | Stop Clock  | time diff 16 min 
74967 | 3/1/2012 | 19:15:00 | Stop Clock  | time diff 0 min 
74970 | 3/1/2012 | 20:15:00 | Pending Active | time diff 60 min 
74972 | 3/1/2012 | 20:21:00 | Active   | time diff 6 min 

如何計算時間差異,其中狀態不是Stop Clock和總結在MySQL中的時間差異?
你可以看到狀態是否爲Stop Clock將停止計數(0分鐘)。

+1

你將需要更好地解釋你想要的東西。顯示您希望看到的輸入數據的輸出。另外,你到目前爲止嘗試過什麼? – 2012-03-15 04:15:04

+0

Field Time的數據類型是什麼? – 2012-03-15 04:41:19

+0

如果您決定使用MySQL自帶的'DATETIME'字段類型,這將是一項非常簡單的任務。 – kba 2012-03-15 05:15:17

回答

1

這個查詢:

select id, date, time, status, hour(diff) * 60 + minute(diff) Diff from (
    select id, date, 
    if(@active or status != 'StopClock', 
     timediff(addtime(date, time), @prevTime), 0) Diff, 
    time(@prevTime := addtime(date, time)) time, 
    @active := status != 'StopClock', 
    status 
    from t, (select @prevTime := 0, @active := false) init 
    order by id 
) final 

會導致:

+-------+------------+----------+---------------+------+ 
| ID | DATE | TIME | STATUS  | DIFF | 
+-------+------------+----------+---------------+------+ 
| 73937 | 2012-03-01 | 17:25:00 | Pending  |  | 
| 73938 | 2012-03-01 | 17:27:00 | Pending  | 2 | 
| 73948 | 2012-03-01 | 17:29:00 | Pending  | 2 | 
| 73952 | 2012-03-01 | 17:45:00 | StopClock  | 16 | 
| 74967 | 2012-03-01 | 19:15:00 | StopClock  | 0 | 
| 74970 | 2012-03-01 | 20:15:00 | PendingActive | 60 | 
| 74972 | 2012-03-01 | 20:21:00 | Active  | 6 | 
+-------+------------+----------+---------------+------+ 

需要注意的是,由於某種原因,你不採取秒鐘考慮。如果您有任何問題,請告訴我。

+0

嗨,你最好....你很好!我已經嘗試了你的代碼,並且正是我期望的!謝謝! – 2012-03-16 12:08:30

+0

歡迎!你應該接受答案,然後:)看到你身邊! – 2012-03-16 12:47:00

+0

@Mosty ...我需要總結'DIFF'列:( – 2012-03-19 07:53:55