MySql中的移动平均线

时间:2016-08-11 08:22:14

标签: mysql

我正在使用MySql并拥有以下格式的数据:

Date       | Product | Value
-----------------------------
2016-01-01 | ProA    | 121.30
2016-01-02 | ProA    | 122.50
2016-01-03 | ProA    | 120.75
2016-01-06 | ProA    | 125.33
2016-01-10 | ProA    | 119.85
-----------------------------

我的要求是一个查询,以获取格式的输出,其中包含上表中的所有列以及' n'的移动平均值。天。它必须从大数据查询。如果' n'输出可以采用以下格式。是3:

Date       | Product | Value  | MovingAvg
-----------------------------------------
2016-01-01 | ProA    | 121.30 | 
2016-01-02 | ProA    | 122.50 | 
2016-01-03 | ProA    | 120.75 | 121.52
2016-01-06 | ProA    | 125.33 | 122.86
2016-01-10 | ProA    | 119.85 | 121.98
-----------------------------------------

此查询适用于我在VB.net中的应用程序 在此先感谢您的帮助

2 个答案:

答案 0 :(得分:2)

这是一个想法。请注意,使用变量的解决方案会快几个数量级......

样本结果集省略了包含少于3个值的平均值,但我将其留作读者的练习......(尽管我已经包含了一些小线索)

SELECT a.date
     , a.product
     , a.value
     , ROUND(AVG(b.value),2) rolling
  FROM 
     ( SELECT x.*
            , COUNT(*) rank
         FROM my_table x
         JOIN my_table y
           ON y.product = x.product
          AND y.date <= x.date 
        GROUP
           BY x.product
            , x.date
     ) a
  LEFT 
  JOIN
     ( SELECT x.*
            , COUNT(*) rank
         FROM my_table x
         JOIN my_table y
           ON y.product = x.product
          AND y.date <= x.date 
        GROUP
           BY x.product
            , x.date
     ) b
    ON b.product = a.product
   AND b.rank BETWEEN a.rank - 2 AND a.rank
 GROUP 
    BY a.date,a.product;

答案 1 :(得分:0)

select a.date
    , a.product
    , a.value
    , round(avg(b.value),2) rolling
 from 
    (
    select x.*
        , count(*) rank 
        from my_table x 

        join my_table y 

        on y.product=x.product 

        and y.date >=x.date

        group 
        by x.product, 
        x.date order by x.date asc
    )
 a


 left
 join 

        (select x.*, 
        count(*) rank 
        from my_table x

        join my_table y

        on y.product = x.product

        and y.date >= x.date

        group 
        by x.product
        , x.date order by x.date asc
    )
    b

    on b.product =a.product 

    and a.rank between b.rank -2 and b.rank

 group 
    by a.date, a.product order by a.date desc;