如何计算SQL中的移动平均值?

时间:2014-11-11 10:07:09

标签: sql sql-server moving-average

我在SQL

中有两列的表格
+------+--------+
| WEEK | OUTPUT |
+------+--------+
|    1 |     10 |
|    2 |     20 |
|    3 |     30 |
|    4 |     40 |
|    5 |     50 |
|    6 |     50 |
+------+--------+

如何计算在2周之前总结输出(例如:在第3周,它将总结第3周,第2周和第1周的输出),我已经看过很多教程要做移动平均线但是他们正在使用日期,在我的情况下,我想使用(int),这可能吗?

谢谢!

5 个答案:

答案 0 :(得分:2)

我想你想要这样的东西:

SELECT *,
       (SELECT Sum(output)
        FROM   table1 b
        WHERE  b.week IN( a.week, a.week - 1, a.week - 2 )) AS SUM
FROM   table1 a 

OR

In子句可以转换为between a.week-2 and a.week

sql fiddle

答案 1 :(得分:1)

您可以使用自我加入。我们的想法是将表放在自身旁边,条件是在一行中添加匹配的行:

SELECT * FROM [output] o1
INNER JOIN [output] o2 ON o1.Week between o2.Week and o2.Week + 2

此选择将产生此​​输出:

o1.Week    o1.Output    o2.Week    o2.Output
--------------------------------------------
1          10           1          10
2          20           1          10
2          20           2          20
3          30           1          10
3          30           2          20
3          30           3          30
4          40           2          20
4          40           3          30
4          40           4          40

等等。请注意,对于第1周和第2周,没有前几周可用。

现在,您应该按o1.Week对数据进行分组,然后获取SUM

SELECT o1.Week, SUM(o2.Output) 
FROM [output] o1
INNER JOIN [output] o2 ON o1.Week between o2.Week and o2.Week + 2
GROUP BY o1.Week

答案 2 :(得分:0)

试试这个:

SELECT SUM(t1.output) / 3
FROM yourtable t1
WHERE t1.week <= 
(select t2.week from yourtable t2 where t2.week - t1.week > 0 and t2.week - t1.week <= 2)

答案 3 :(得分:0)

如果周是连续的,您可以简单地使用窗口函数

SELECT [Week], [Output], 
    SUM([Output]) OVER (ORDER BY [Week] ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM dbo.SomeTable

范围对于计算更准确,但尚未在SQL Server中实现。其他数据库引擎可能支持

SELECT [Week], [Output], 
    SUM([Output]) OVER (ORDER BY [Week] RANGE BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM dbo.SomeTable

答案 4 :(得分:0)

你没有编写你的sql server,如果它是sql server 2012或更高版本,那么简单的例子就是

declare @table table(wk int,outpt int )

insert into @table values (1,10)
,(2,20)
,(3,30)
,(4,40)
,(5,50)
,(6,60)

select *,SUM(outpt) over(partition by id order by id rows between unbounded  preceding and current row  ) dd
from (
select * , 1 id
from @table
where wk < 5
) a