如何计算T-SQL中的移动/滚动平均值

时间:2013-09-20 09:30:13

标签: sql-server tsql calculated-columns moving-average

我的SQL表中有年度数据(明天)。我想计算3个月的滚动/移动平均值。如何做到这一点?

1 个答案:

答案 0 :(得分:0)

也许这会给你一个建议。

drop table #temp

;with cte as
(
    select 1 as id
    union all
    select id + 1 from cte
    where id < 100
)
select 
    *, id / 10 as "year", null as "rolSum"
into #temp
from 
    cte 
where 
    id < 100

select "year", id from #temp order by "year"


declare @rolSum int = 0
update #temp set @rolSum = "rolSum" = @rolSum + id from #temp

select year, id, rolSum, avg( id * 1.0 ) over ( partition by "year" order by id ) from #temp
如果rolSum无法满足您的需求,

avg(...)仅用于进一步处理。