Well, I can't do it i only 2 queries, but if that is not a requirement, this might work for you:declare @param int=100;select a.seq ,a.ticker ,case when sum(b.qty)>@param then @param-(sum(b.qty)-a.qty) else a.qty end as qty into #temptable from table1 as a inner join table1 as b on b.ticker=a.ticker and b.seq<=a.seq group by a.ticker ,a.seq ,a.qty having sum(b.qty)-a.qty<@param;delete from table1 where exists (select 1 from #temptable where #temptable.ticker=table1.ticker and #temptable.seq=table1.seq and #temptable.qty=table1.qty );update a set a.qty=a.qty-b.qty from table1 as a inner join #temptable as b on b.ticker=a.ticker and b.seq=a.seq;update a set a.qty=a.qty+b.qty from table2 as a inner join #temptable as b on b.ticker=a.ticker and b.seq=a.seq;insert into table2 select * from #temptable as a where not exists (select 1 from table2 as b where b.ticker=a.ticker and b.seq=a.seq );drop table #temptable;