可以在小提琴中使用的快速设置。
create table tbl
(avgdate date, avgvalue numeric(10,2));
insert into tbl values ('2021-01-01',10.4);
insert into tbl values ('2021-01-02',13.1);
insert into tbl values ('2021-01-03',11.35);
insert into tbl values ('2021-01-04',3.4);
insert into tbl values ('2021-01-05',7.12);
insert into tbl values ('2021-01-06',16.76);
insert into tbl values ('2021-01-07',17.2);
insert into tbl values ('2021-01-08',13.76);
insert into tbl values ('2021-01-09',10.56);
insert into tbl values ('2021-01-10',null);
insert into tbl values ('2021-01-11',null);
insert into tbl values ('2021-01-12',null);
我想写一些类似的东西
select avgdate,
case when avgvalue is not null then avgvalue
else
--avg of past 7 days
end
from tbl
通常我会使用滞后函数或 rownumber 来挑选前面的行值并将它们平均,这适用于第 10 行,但我的逻辑在需要包括计算行时遇到了错误。 1 月 12 日应该是 5 日到 9 日的平均值,加上 10 日和 11 日的计算值。
答案 0 :(得分:1)
这几乎就是您想要的代码:
coalesce(avgvalue,
avg(avgvalue) over (order by date rows between 7 preceding and 1 preceding)
)
等等。这会选择前 7 个值,其中一些可能是 NULL
。您可以将 apply
用于此目的:
select t.*,
coalesce(t.avgvalue, t2.avgvalue7)
from tbl t outer apply
(select avg(t2.avgvalue) as avgvalue7
from (select top (7) t2.avgvalue
from tbl t2
where t2.avgvalue is not null and
t2.date < t.date
order by t2.date desc
) t2
) t2;