2017-01-03 40 views
3

我需要計算數據庫中存儲的所有操作的平均時間。我存儲在外觀還是操作如下表:存儲在數據庫中的平均操作時間

creation time  | operation_type | operation_id 
2017-01-03 11:14:25 | START   | 1 
2017-01-03 11:14:26 | START   | 2 
2017-01-03 11:14:28 | END   | 2 
2017-01-03 11:14:30 | END   | 1 

在這種情況下,操作1用了5秒,動作2用了2秒完成。

如何計算MySQL中這些操作的平均值?

編輯: 看來operation_id不必是唯一的 - 給定的操作可以被執行多次,所以表可能如下所示:

creation time  | operation_type | operation_id 
2017-01-03 11:14:25 | START   | 1 
2017-01-03 11:14:26 | START   | 2 
2017-01-03 11:14:28 | END   | 2 
2017-01-03 11:14:30 | END   | 1 
2017-01-03 11:15:00 | START   | 1 
2017-01-03 11:15:10 | END   | 1 

我應該在查詢添加到正確計算所有這些操作的平均時間?

回答

2

我不知道,一個子查詢是必要的......

SELECT AVG(TIME_TO_SEC(y.creation_time)-TIME_TO_SEC(x.creation_time)) avg_diff 
    FROM my_table x 
    JOIN my_table y 
    ON y.operation_id = x.operation_id 
    AND y.operation_type = 'end' 
WHERE x.operation_type = 'start'; 
+0

謝謝,這是最好的和最簡單的解決方案!你知道我該如何修改這個查詢來考慮一個事實,即operation_id不是唯一的?我今天編輯了原始問題,併發布了表格的外觀。 – CorrieSparrow

+0

我的示例依賴於您在(operation_type,operation_id)上形成了PRIMARY KEY的事實, – Strawberry

2

由於操作的結束總是啓動後,您可以使用MIN和MAX

select avg(diff) 
from 
(
     select operation_id, 
      TIME_TO_SEC(TIMEDIFF(max(creation_time), min(creation_time))) as diff 
     from your_table 
     group by operation_id 
) tmp 
+0

接受的答案是一樣的 - 似乎工作。 –

+0

好的 - 你說得對。我添加了'TIME_TO_SEC'以在幾秒鐘內獲得最終結果。 –

1
select avg(diff) 
from 
(
select a1.operation_id, timediff(a2.operation_time, a1.operation_time) as diff 
from oper a1 -- No table name provided, went with 'oper' because it made sense in my head 
inner join oper a2 
    on a1.operation_id = a2.operation_id 
where a1.operation_type = 'START' 
and a2.operation_type = 'END' 
)