2

我需要根据时间戳计算行的平均值并按 field1 分组。例如,我有一张桌子

Field1      Field2      TImeStamp
  X           X1    11/19/2012 12:21:32
  X           X2    11/19/2012 12:22:32
  X           X3    11/19/2012 12:24:32
  Y           Y1    11/19/2012 12:21:32
  Y           Y2    11/19/2012 12:22:32
  Y           Y3    11/19/2012 12:23:32
  Y           Y4    11/19/2012 12:24:32

我有这种带有时间戳的表,它与当前时间以及其他字段一起插入。现在我想根据时间戳计算平均值。例如,我想在特定持续时间内获得最新的平均值 + 另一个平均值。在上述情况下,我想要:

Fields   Averaged function
  X        (X3+(X1+X2)/2)/2
  Y        (Y4+(Y1+Y2+Y3)/3)/2

对于以上内容,我必须计算(现在 + 平均值(现在 - 1 分钟到现在 - 5 分钟))的平均值。我怎样才能做到这一点?

4

1 回答 1

1

我认为这会做到:

select field1, if(avgf2 = 0,maxf2,(maxf2+avgf2)/2) avgfun
from (select m.field1 field1,
             max(if(timestamp = maxts, field2, null)) maxf2,
             coalesce(avg(if(timestamp = maxts, null, field2)),0) avgf2
      from mytable m
      join (select field1, max(timestamp) maxts
            from mytable
            where timestamp between date_sub(now(), interval 5 minute) and now()
            group by field1) mm
      using (field1)
      where timestamp between date_sub(now(), interval 5 minute) and now()
      group by field1) x

关键是像 MAX 和 AVG 这样的聚合函数会忽略 NULL。

要仅检查特定时间范围,请插入WHERE timestamp BETWEEN <begin> AND <end>两个子查询。

于 2012-11-19T05:59:45.547 回答