create table #tab(aa int,bb nvarchar(10),cc int,dd int)
insert into #tab(aa,bb,cc,dd) select 1,'b',1,12
insert into #tab(aa,bb,cc,dd) select 2,'c',1,20
insert into #tab(aa,bb,cc,dd) select 3,'b',2,20
insert into #tab(aa,bb,cc,dd) select 4,'d',1,30
insert into #tab(aa,bb,cc,dd) select 5,'a',1,40
insert into #tab(aa,bb,cc,dd) select 6,'d',2,10
insert into #tab(aa,bb,cc,dd) select 7,'d',3,12
insert into #tab(aa,bb,cc,dd) select 8,'c',2,-11
insert into #tab(aa,bb,cc,dd) select 9,'a',2,12
insert into #tab(aa,bb,cc,dd) select 10,'b',3,-10
insert into #tab(aa,bb,cc,dd) select 11,'d',4,-10
select * from #tab order by bb,aa
declare @aa int
declare @bb varchar(10)
declare @dd int
declare curdel cursor static for
select aa,bb,dd from #tab where dd < 0
open curdel
fetch next from curdel into @aa,@bb,@dd
while @@fetch_status = 0
begin
update #tab set dd = dd + @dd where bb = @bb and aa = (select max(aa) from #tab where bb= @bb and aa < @aa)
delete from #tab where bb = @bb and aa = @aa
fetch next from curdel into @aa,@bb,@dd
end
close curdel
deallocate curdel
select * from #tab order by bb ,aa
drop table #tab