问题描述
我正在尝试计算sql Server数据库中多个字段随时间变化的不规则间隔的移动平均值。我意识到,对于规则间隔的数据,我可以使用@H_404_1@SELECT grp,AVG(count) FROM t ... OVER (PARTITION BY grp ... ROWS 7 PRECEDING)来创建前一周数据的移动平均值。但是,我的数据组织如下:
@H_404_1@DATE GRP COUNT 2018-07-05 1 10 2018-07-08 1 4 2018-07-11 1 6 2018-07-12 1 6 2018-07-11 2 5 2018-07-15 2 10 2018-07-17 2 8 2018-07-20 2 10 ...
对于大多数组来说,在某些日期没有观测值。我正在寻找的输出是:
@H_404_1@DATE GRP MOVING_AVG 2018-07-05 1 10 2018-07-08 1 7 2018-07-11 1 6.67 2018-07-13 1 5.33 2018-07-11 2 5 2018-07-15 2 7.5 2018-07-16 2 7.67 2018-07-20 2 9.33
是否可以在@H_404_1@PRECEDING子句中指定日期而不是行,还是必须创建某种掩码以求平均?
根据注释进行了澄清编辑
解决方法
在SQL Server中,我认为这可以通过横向联接来实现:
select
date,grp,(
select avg(count)
from mytable t1
where
t1.grp = t.grp
and t1.date >= dateadd(year,-1,t.date)
and t1.date <= t.date
) as cnt
from mytable
,
如果我没有误会。您需要7天或其他任何天,但要在日期前添加行。
DATE GRP COUNT
2018-07-11 2 5
2018-07-15 2 10
2018-07-17 2 8
2018-07-20 2 10 <--- the AVG of this row must include 7 days before,so 2018-07-11 not include
在这种情况下:
select
date,(
select avg(count)
from t t1
where
t1.grp = t.grp
and DATEDIFF(day,t1.date,t.date) <= 7 /*7 or whatever day you want*/
and t1.date <= t.date
) as MOVING_AVG
from t