3

我正在尝试计算 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";
4

2 回答 2

0

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

于 2013-05-20T12:01:51.240 回答
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 表并替换为

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 视图不支持联合视图可能是一个错误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
于 2013-05-20T14:55:18.170 回答