LeetCode 1161.每台机器的进程平均运行时间

数据准备

drop table Activity;

Create table If Not Exists Activity (machine_id int, process_id int, activity_type ENUM('start', 'end'), timestamp float);
Truncate table Activity;
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('0', '0', 'start', '0.712');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('0', '0', 'end', '1.52');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('0', '1', 'start', '3.14');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('0', '1', 'end', '4.12');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('1', '0', 'start', '0.55');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('1', '0', 'end', '1.55');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('1', '1', 'start', '0.43');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('1', '1', 'end', '1.42');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('2', '0', 'start', '4.1');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('2', '0', 'end', '4.512');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('2', '1', 'start', '2.5');
insert into Activity (machine_id, process_id, activity_type, timestamp) values ('2', '1', 'end', '5');

需求

在有一个工厂网站由几台机器运行,每台机器上运行着相同数量的进程. 请写出一条SQL计算每台机器各自完成一个进程任务的平均耗时.

完成一个进程任务的时间指进程的’end’ 时间戳 减去 ‘start’ 时间戳. 平均耗时通过计算每台机器上所有进程任务的总耗费时间除以机器上的总进程数量获得.

结果表必须包含machine_id(机器ID) 和对应的 average time(平均耗时) 别名 processing_time, 且四舍五入保留3位小数.

输入

LeetCode 1161.每台机器的进程平均运行时间_第1张图片

分析

/*
  将Activity自关联,分别为a1和a2,
  其中a1其activity_type='start'的表
  其中a2其activity_type='end'的表
  同时增加一列a2.timestamp-a1.timestamp,获取每个进程运行的时间
  再以machine_id进行分组,获取每个机器运行的平均时间
 */

输出

with t1 as (
    select distinct a1.machine_id,a1.process_id,
                a2.timestamp-a1.timestamp as rn1
    from Activity a1,Activity a2
    where a1.machine_id=a2.machine_id and a1.process_id=a2.process_id
      and a1.activity_type='start'
      and a2.activity_type='end'
)
select machine_id,
       round(sum(rn1) / count(1),3) as processing_time
from t1
group by machine_id;

LeetCode 1161.每台机器的进程平均运行时间_第2张图片

你可能感兴趣的:(数据库,数据结构,mysql,leetcode)