2017-01-03 52 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' 
)