0

我有以下查询计算 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;

查询应该是什么?

4

1 回答 1

1

我对此的抨击:

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

于 2013-03-04T21:56:39.903 回答