我需要在MySQL中比较3周的标准偏差

时间:2018-08-04 19:49:48

标签: mysql sql

我有下面的源表:

date        Growthrate
----------  ----------
2015-04-05, 0.4
2015-04-12, 0.3
2015-04-19, 0.2
2015-04-26, 0.7
2015-05-03, 0.8
2015-05-10, 0.9
2015-05-17, 0.8
2015-05-24, 0.2
2015-05-31, 0.6

目标表应为:

WeekNumber, result
1, 
2, 
3, good
4, poor

与过去3周相比,如果增长率为2 stdev,则结果值很好

1 个答案:

答案 0 :(得分:0)

这是棘手的,因为要计算窗口标准偏差。我假设一旦有了,case表达式就变得微不足道了。

您希望能够做到:

select t.*,
       (select std(t2.growthrate)
        from (select t2.*
              from t t2
              where t2.weeknumber <= t.weeknumber and t2.weeknumber >= t.weeknumber - 2
              order by t2.weeknumber desc
              limit 3
             )
       ) as std
from t;

MySQL不允许您这样做。因此,您陷入了join

select t.weeknumber, t.growthrate,
       std(t2.growthrate) as std,
       avg(t2.growthrate) as avg
from t join
     t t2
     where t2.weeknumber <= t.weeknumber and
           t2.weeknumber >= t.weeknumber - 2
group by t.weeknumber, t.growthrate;

说了这么多,我认为使用基于三点的标准差是错误的。