Here's one option...--structuredeclare @TableA table ( Orderid int, total_qty smallint, total_deduction decimal(18,2))declare @TableB table ( TransDate datetime, Orderid int, single_deductions decimal(18,2), deduction_remaining decimal(18,2))--/--datainsert @TableA (Orderid, Total_Qty, Total_Deduction) select 1, 2, 60union all select 2, 3, 100insert @TableB (Transdate, Orderid, Single_deductions, Deduction_Remaining) select '20090917', 1, 45, 0union all select '20090917', 1, 5, 0union all select '20090917', 2, 11, 0--/--calculation; with t1 as (select Orderid, sum(single_deductions) as deductions from @TableB group by Orderid), t2 as (select b.*, (a.total_deduction - b.deductions) / a.Total_Qty as New_Deduction_Remaining from @TableA a inner join t1 b on a.Orderid = b.Orderid), t3 as (select a.*, New_Deduction_Remaining from @TableB a inner join t2 b on a.Orderid = b.Orderid)update t3 set Deduction_Remaining = New_Deduction_Remaining--/--outputselect * from @TableB/*TransDate Orderid single_deductions deduction_remaining----------- -------- ------------------ --------------------2009-09-17 1 45.00 5.002009-09-17 1 5.00 5.002009-09-17 2 11.00 29.67*/--/
Ryan Randall Solutions are easy. Understanding the problem, now, that's the hard part.