你好,我有一张桌子的数据,我正在寻找移动平均线。
原始数据
date qty
06/11/15 5
08/11/15 7
09/11/15 8
10/11/15 12
11/11/15 34
15/11/15 45
16/11/15 12
17/11/15 7
移动平均线应该考虑最近90天的数据并给出我当前数据的平均值,如下所示
Moving Average Data
date qty movingAvg
06/11/15 5 5
07/11/15 0 2.5
08/11/15 7 4
09/11/15 8 5
10/11/15 12 6.4
11/11/15 34 11
12/11/15 0 9.43
13/11/15 0 8.25
14/11/15 0 7.33
15/11/15 45 11.1
16/11/15 12 11.18
17/11/15 7 10.83
我正在使用的查询
SELECT t1.date,t1.qty, AVG(t2.qty) AS 'movingAvg'
FROM tbl t1
JOIN tbl t2 ON t1.company_id=t2.company_id
AND DATEDIFF(t1.date, t2.date) BETWEEN 0 AND 90
WHERE t1.company_id=1234
GROUP BY t1.date
ORDER BY t1.date;
忽略了没有输入的日期,我也想包括它们。
答案 0 :(得分:0)
像这样使用MySQL Str_to_date
Str_to_date(t1.date,'%d/%m/%y')
或更改此
DATEDIFF(Str_to_date(t1.date,'%d/%m/%y'), Str_to_date(t2.date,'%d/%m/%y'))
MySQL
STR_TO_DATE()
函数将字符串转换为日期时间 值