running average in mysql

后端 未结 4 1277
刺人心
刺人心 2021-01-25 06:15

I have the table like below

id   timestamp  speed
1    11:00:01   100
2    11:05:01   110
3    11:10:01   90
4    11:15 :01  80

I need to calcu

4条回答
  •  粉色の甜心
    2021-01-25 07:09

    Your query is one way to do a running average:

    SELECT t.*,
           (select avg(speed) from tbl tt where tt.timestamp <= t.timestamp) as avg
    FROM tbl t;
    

    The alternative is to use variables:

    select t.*, (sum_speed / cnt) as running_avg_speed
    from (select t.*, (@rn := @rn + 1) as cnt, (@s := @s + speed) as sum_speed
          from tbl t cross join
               (select @rn := 0, @s := 0) params
          order by timestamp
         ) t;
    

    An index on tbl(timestamp) should further improve performance.

提交回复
热议问题