MySQL移动平均值的时间序列

时间:2015-01-26 05:32:12

标签: mysql

我试图计算表格中包含的时间序列的移动平均线(7天和30天):' mass'字段:' date',' time'和' lbs'。

虽然我怀疑这不是理想的MySQL,但以下代码可以生成一个包含每个日期正确值的正确临时表(' mov')。

CREATE TEMPORARY TABLE IF NOT EXISTS mov
(   date DATE NOT NULL PRIMARY KEY,
    lbs FLOAT(12),
    ma7d FLOAT(12),
    ma30d FLOAT(12)
) AS

# Calculates moving averages
SELECT t1.date, t1.lbs,
( SELECT SUM(t2.lbs) / COUNT(t2.lbs) FROM mass AS t2 
WHERE DATEDIFF(t1.date, t2.date) BETWEEN 0 AND 6 ) AS 'ma7d', 
( SELECT SUM(t2.lbs) / COUNT(t2.lbs) FROM mass AS t2 
WHERE DATEDIFF(t1.date, t2.date) BETWEEN 0 AND 29 ) AS 'ma30d' 
FROM mass AS t1;

SELECT * FROM mov
GROUP BY date
ORDER BY date;

我的基本问题(我刚开始学习MySQL!)是:  我现在如何插入' ma7d'并且' ma30d'值为原始表格中的相应日期'质量'?

我的目标是定期运行此脚本,以更新“#mass”。随着新数据的添加。

非常感谢。

0 个答案:

没有答案