一般是写一个存储过程,用个游标循环每条处理,很容易就搞定了。以后变动也灵活。
如果不用存储过程,单SQL语句实现,可以这样:
update salary t1
set t1.s = (select sum(t2.s)
from salary t2
where t2.year >=add_month(t1.year,-24)
and t2.year <=add_month(t1.year,-12)
);
不知道用开窗函数可以不,可以验证下
select year,sum(salary)over(order by salary rows between 2 preceding and 1 preceding ) --前两行到前一行的和
from salay
作业题吧
select a.year,ns=isnull((select s from salary where datediff(yy,year,a.year)=1),0)+
isnull((select s from salary where datediff(yy,year,a.year)=2),0)
from salary a
一楼的牛!