如何创建滚动平均数据?

时间:2014-09-27 10:49:13

标签: sql sql-server sql-server-2008 sas moving-average

我有一张这样的表:

Week prod Value
1    A     2.3
1    B     4.1
1    C     6.3
2    A     0
2    B     3.4
2    C     1.4
3    A     4.2
3    B     2.5
3    C     6.7

现在我有很多周的类似数据,我想卷起来说3周1,2,3并将其作为第1周,然后取平均价值(A,B,C),就像下一卷上升2,3,4,并使其成为第2周的平均值,并持续到上周。

2 个答案:

答案 0 :(得分:1)

许多数据库支持ANSI标准窗口函数:

with weeks as (
      select week, sum(value) as value
      from table t
      group by week
     )
select week, value,
       avg(value) over (order by week range between 2 preceding and current row) as avg_3week
from weeks;

编辑:

您可以使用子查询来编写它:

select week, value,
       avg(value) over (order by week range between 2 preceding and current row) as avg_3week
from (select week, sum(value) as value
      from table t
      group by week
     ) weeks;

您可能需要在SAS中将其作为传递查询。 proc sql不执行窗口函数。

答案 1 :(得分:0)

试试这个:

select id, avg(avg(val)) over(order by id ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
  from t
 group by id

SQLFiddle

如果不支持滚动窗口,您可以使用:

with tt(id, aval) as (
  select id, avg(val)
    from t
   group by id
)
select id, (select avg(aval) from tt tt1 where tt1.id between tt2.id and tt2.id + 2)
  from tt tt2

SQLFiddle

没有CTE:

select distinct id, (select avg(aval) 
              from (select id, avg(val) aval
                      from t
                     group by id
                   ) tt1 
             where tt1.id between tt2.id and tt2.id + 2)
  from t tt2

SQLFiddle