计算5天移动平均线 - 如果日期之间存在间隙,则将值设置为0。

时间:2013-05-20 11:55:16

标签: php mysql moving-average

我正在计算5天移动平均线。一切正常,除非日期之间存在差距。如果存在间隙,则应将缺失日期(-s)的值设置为零,以显示正确的移动平均值。

这是我的表(orders_total),您可以看到没有1/7/13的日期,这导致了问题:

orders_id    value    date
1            199      1/1/13 0:00
2            199      1/2/13 0:00
3            199      1/3/13 0:00
4            199      1/4/13 0:00
5            249      1/5/13 0:00
6            199      1/6/13 0:00
7            199      1/8/13 0:00
8            199      1/9/13 0:00
9            199      1/10/13 0:00
10           199      1/11/13 0:00
11           199      1/12/13 0:00
12           199      1/13/13 0:00

如果缺失日期1/7/13的值设置为零,则正确的5天移动平均线(正在寻找)是:

199
199
199
199
209
209
169.2
169.2
169.2
159.2
159.2
199
199

这是我正在使用的代码,当日期之间存在差距时,它没有显示正确的移动平均线:

    SELECT ot1.value, ot1.date,
    (SELECT SUM(ot2.value) / COUNT(ot2.value)
    FROM orders_total AS ot2 WHERE DATEDIFF(ot1.date, ot2.date) BETWEEN 0 AND 4) AS '5dayMovingAvg'
    FROM orders_total AS ot1 ORDER BY ot1.date";

2 个答案:

答案 0 :(得分:0)

如果您知道它总是5天,为什么除以COUNT(ot2.value)?除非您尝试处理边缘情况,否则处理边缘情况的方式与正常情况不同。

答案 1 :(得分:0)

尝试此查询:

SELECT ot1.value, ot1.date,
            (    SELECT SUM(ot2.value) / COUNT(ot2.value)
            FROM (

     select * from orders_total union
        (SELECT 0 as order_id,0 as `value`,DATE(r1.date) + INTERVAL 1 DAY AS missing_date
        FROM orders_total r1
        LEFT OUTER JOIN orders_total r2 ON DATE(r1.date) = DATE(r2.date) - INTERVAL 1 DAY 
        WHERE r2.date IS NULL )

) AS ot2 WHERE DATEDIFF(ot1.date, ot2.date) BETWEEN 0 AND 4) AS '5dayMovingAvg'
            FROM (

    select * from orders_total union
        (SELECT 0 as order_id,0 as `value`,DATE(r1.date) + INTERVAL 1 DAY AS missing_date
        FROM orders_total r1
        LEFT OUTER JOIN orders_total r2 ON DATE(r1.date) = DATE(r2.date) - INTERVAL 1 DAY 
        WHERE r2.date IS NULL )

) 

        AS ot1 ORDER BY ot1.date

基本上我所做的是我已经从您的查​​询中替换了orders_total tabel并替换为

select * from orders_total union
        (SELECT 0 as order_id,0 as `value`,DATE(r1.date) + INTERVAL 1 DAY AS missing_date
        FROM orders_total r1
        LEFT OUTER JOIN orders_total r2 ON DATE(r1.date) = DATE(r2.date) - INTERVAL 1 DAY 
        WHERE r2.date IS NULL )

这个查询,我本可以将它放在视图中但是mysql视图不支持视图中的union可能是一个bug http://bugs.mysql.com/bug.php?id=9198

注意:这还包括一个额外的行,您可以使用max(date)

将其排除

来自上述查询的结果:

199 2013-01-01 00:00:00 199.0000
199 2013-01-02 00:00:00 199.0000
199 2013-01-03 00:00:00 199.0000
199 2013-01-04 00:00:00 199.0000
249 2013-01-05 00:00:00 209.0000
199 2013-01-06 00:00:00 209.0000
0   2013-01-07 00:00:00 169.2000
199 2013-01-08 00:00:00 169.2000
199 2013-01-09 00:00:00 169.2000
199 2013-01-10 00:00:00 159.2000
199 2013-01-11 00:00:00 159.2000
199 2013-01-12 00:00:00 199.0000
199 2013-01-13 00:00:00 199.0000
0   2013-01-14 00:00:00 159.2000