题目来源:
leetcode题目,网址:1661. 每台机器的进程平均运行时间 - 力扣(LeetCode)
解题思路:
首先根据 machine_id 进行分组聚合,对于组内数据,先计算差值之和在求平均值,最后输出即可。
求差值之和,利用 sum() 和 case when end 在 activity_type 为 end 时加上 timestamp,否则加上 -1*timestamp 。
计算平均值:差值之和/进程数,差值之和由上一步求出,进程数有 count(distinct process_id) 得出。
解题代码:
# Write your MySQL query statement below
select machine_id,
round(
sum(
case activity_type
when 'start' then -1*timestamp
when 'end' then timestamp
else 0
end)/count(distinct process_id),3) as processing_time
from Activity
group by machine_id
总结:
无官方题解。
看了下其它人的题解,发现case when else 可以用 if(expression,trueThen,falseThen) 代替,也就是 sum(case ...when... end) 可以写成 sum(if(activity_type='start',-timestamp,timestamp)),试了下,可以通过,而且运行时间缩短了。