我最初的反应是使用LIMIT将平均值限制为5个结果,这使我建议:
select a.host,avg(a.execution_time) from (select id,execution_time,host from jobs order by id desc limit 5) a group by a.host;
但是很明显,这将平均数限制为每个主机最近的5个工作,而不是最近的5个工作.
如果不使用某种存储过程,似乎很难使用LIMIT来限制平均值.这使我考虑使用MysqL变量为每个作业分配每个主机的完成顺序或职位.
这未经测试,但是它说明的理论应该是一个很好的起点:
首先,我们应该根据作业的主机为每个作业分配一个职位:
select
host,@current_pos := if (@current_host = host,@current_pos,0) + 1 as position,@current_host := host
from
(select @current_host := null,@current_pos := 0) set_pos,jobs
order by
host,id desc;
建立位置后,只需选择聚合函数,将结果限制在前5位:
select
jt.host,avg(jt.execution_time)
from
(
select
host,@current_host := host
from
(select @current_host := null,jobs
order by
host,id desc
) jt
where
jt.position <= 5
group
by host;
请让我知道这是否适合您,或者还有更多我未考虑的方面.这是一个有趣的问题.