简体   繁体   English

在SQL中计算移动平均值

[英]Calculate moving averages in SQL

I want to calculate a 12 month moving average from a MySQL column. 我想从MySQL专栏计算12个月的移动平均线。 The data represents time-series power measurements, it is a largish dataset (every 10 minutes for several years). 数据代表时间序列功率测量,它是一个较大的数据集(几年内每10分钟一次)。 A high performance query would be nice but speed is something I can work out later. 一个高性能的查询会很好,但速度是我以后可以解决的问题。

DTE                  Active
2012-1-3 00:10       500
2012-1-3 00:20       520
... etc

The following query gives me the total Active for each month : 以下查询为我提供了每月的活动总数:

SELECT YEAR(DTE) AS year, MONTH(DTE) AS month, SUM(Active)/6 as total FROM saturne s GROUP BY YEAR(DTE), MONTH(DTE)

The following query gives me the moving average Active for a given month and year - say october 2011 以下查询给出了给定月份和年份的移动平均值 - 例如2011年10月

SELECT SUM(Active)/6 AS average FROM saturne 
WHERE (YEAR(DTE) = 2011 AND MONTH(DTE) <= 10) OR (YEAR(DTE) = 2010 AND MONTH(DTE) > 10) 

I would however like to generate a query which returns the monthly total and the 12 month moving average in the next column. 但是,我想生成一个查询,该查询返回下一列中的每月总计和12个月移动平均值。

year        month        total        average
2012        2            701474       9258089
2012        1            877535       9386664
... etc

(The factor of 6 is because the data represents instantaneous power recorded every 10 minutes, dividing the total by 6 gives the total energy) (因子6是因为数据表示每10分钟记录一次的瞬时功率,将总数除以6给出总能量)

Try: 尝试:

SELECT YEAR(GDTE) AS year, 
       MONTH(GDTE) AS month, 
       SUM(case when i=0 then Active end)/6 as total,
       SUM(Active)/(MAX(i+1)*6) as avg
FROM
(select s.*, DATE_ADD(DTE, INTERVAL m.i MONTH) GDTE, m.i
 FROM saturne s
 cross join (select 0 i union select 1 union select 2 union select 3 union 
             select 4 union select 5 union select 6 union select 7 union 
             select 8 union select 9 union select 10 union select 11) m
) sq
WHERE GDTE <= curdate()
GROUP BY YEAR(GDTE), MONTH(GDTE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM