现在有一个工厂网站由几台机器运行,每台机器上运行着相同数量的进程. 请写出一条SQL计算每台机器各自完成一个进程任务的平均耗时.
完成一个进程任务的时间指进程的'end' 时间戳 减去 'start' 时间戳. 平均耗时通过计算每台机器上所有进程任务的总耗费时间除以机器上的总进程数量获得.
结果表必须包含machine_id(机器ID) 和对应的 average time(平均耗时) 别名 processing_time, 且四舍五入保留3位小数.
具体参考例子如下:
Activity table:
+------------+------------+---------------+-----------+
| machine_id | process_id | activity_type | timestamp |
+------------+------------+---------------+-----------+
| 0 | 0 | start | 0.712 |
| 0 | 0 | end | 1.520 |
| 0 | 1 | start | 3.140 |
| 0 | 1 | end | 4.120 |
| 1 | 0 | start | 0.550 |
| 1 | 0 | end | 1.550 |
| 1 | 1 | start | 0.430 |
| 1 | 1 | end | 1.420 |
| 2 | 0 | start | 4.100 |
| 2 | 0 | end | 4.512 |
| 2 | 1 | start | 2.500 |
| 2 | 1 | end | 5.000 |
+------------+------------+---------------+-----------+
Result table:
+------------+-----------------+
| machine_id | processing_time |
+------------+-----------------+
| 0 | 0.894 |
| 1 | 0.995 |
| 2 | 1.456 |
+------------+-----------------+
一共有3台机器,每台机器运行着两个进程.
机器 0 的平均耗时: ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
机器 1 的平均耗时: ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
机器 2 的平均耗时: ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/average-time-of-process-per-machine
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# Write your MySQL query statement below
#本题为典型的一张表内加减,常规解法,自连接,注意可直接用avg来求平均值,
select a1.machine_id,round(avg(a2.timestamp-a1.timestamp),3) processing_time
from activity a1
join activity a2
on a1.machine_id=a2.machine_id
where a1.process_id=a2.process_id and a1.activity_type<>a2.activity_type and a1.activity_type='start'
group by a1.machine_id