我有以下查询计算5天的简单移动平均线。我想将查询更改为5天的指数移动平均值
DROP TABLE IF EXISTS t;
CREATE TABLE t (id int,item int, dt DATE, qty INT);
INSERT INTO t VALUES
(1,1,'2007-1-1',5),
(2,1,'2007-1-2',6),
(3,1,'2007-1-3',7),
(4,1,'2007-1-4',8),
(5,1,'2007-1-5',9),
(6,1,'2007-1-6',10),
(7,1,'2007-1-7',11),
(8,1,'2007-1-8',12),
(9,1,'2007-1-9',13),
(10,2,'2007-1-1',6),
(11,2,'2007-1-2',7),
(12,2,'2007-1-3',8),
(13,2,'2007-1-4',9),
(14,2,'2007-1-5',10),
(15,2,'2007-1-6',11),
(16,2,'2007-1-7',12),
(17,2,'2007-1-8',13),
(18,2,'2007-1-9',14);
SELECT
t1.id,t1.item,t1.dt,t1.qty,
( SELECT SUM(t2.qty) / COUNT(t2.qty)
FROM t AS t2
WHERE t1.id - t2.id =4
) AS '5daySMA'
FROM t AS t1
GROUP BY t1.item,t1.dt;
应该查询什么?
答案 0 :(得分:0)
我的抨击:
select dt,
@a := ( @a*.667 + qty*.333) AS moving_avg
from t
Join (select @a := 0) as X
order by dt desc
.333是k = 2 /(N + 1),其中N是5天时间
.667是(1-k),见EMA公式
EMA =价格(t)* k + EMA(y)*(1 - k)
@a:= 0部分应该改为合理#否则在开始时会出现偏差
源于此讨论,您可以在那里查找更多详细信息 http://grokbase.com/t/mysql/mysql/127gbqzkyj/trouble-with-average