计算过去 7 天 mysql 的平均时间

Calculate avg time in mysql from last 7 days

Tablename=run_detail

I have to calculate avg time of jobs for last 7 days, but in somecases number of runs could be less than 7 days. eg abc has only 2 run_date. (4.5+6+.....+7)/7=5.83 and (23.9+45.7)/2=34.8 and also need to calculate based on latest 7 runs. for eg. 2020-07-04 to 2020-07-10, not from 2020-07-01

Job_name run_date   rownum count  elapsed_time(sec) avg_time
xyz      2020-07-01   1     10       4.5             ?
xyz      2020-07-02   2     10       6               ?
.......  
xyz      2020-07-10   10    10       7.0             ?
abc      2020-07-01   1      2       23.9            ?
abc      2020-07-02   2      2       45.7            ?

Desired Output

Job_name run_date   rownum count  elapsed_time(sec) avg_time
xyz      2020-07-01   1     10       4.5             5.83
xyz      2020-07-02   2     10       6               5.83
.......  
xyz      2020-07-10   10    10       7.0             5.83
abc      2020-07-01   1      2       23.9            34.8
abc      2020-07-02   2      2       45.7            34.8

Could you please help how to achieve the avg time in mysql

如果您想要前 7 天的超额,您可以使用 window 函数:

select t.*,
       avg(elapsed_time) over (partition by job_name
                               order by run_date
                               range between interval -6 day preceding and current row
                              ) as avg_time
from t;

注意:这假定您确实需要前六天加上当前日期。如果你真的想要 7 天前到 1 天前(前一周),那么使用:

range between interval -7 day preceding and interval -1 day preceding

编辑:

在 MySQL 的旧版本中,您可以使用相关子查询:

select t.*,
       (select avg(t2.elapsed_time)
        from t t2
        where t2.job_name = t.job_name and
              t2.run_date <= t.run_date and
              t2.run_date > t.run_date - interval 7 day
       ) as avg_time
from t;

调整日期比较以获得您想要的准确时间段。