I think that the Transactions table requires an additional column for ordering, something like this:
Create table #Trans1(ConsumerID INT, Transamount decimal(18,2), OrdNum int)
INSERT INTO #Trans1
SELECT 1001,9,1 UNION ALL
SELECT 1001,4,2 UNION ALL
SELECT 1001,3,3 UNION ALL
SELECT 1002,15,1 UNION ALL
SELECT 1003,20,1 UNION ALL
SELECT 1003,1,2 UNION ALL
SELECT 1003,5,3
Then the long solution is:
;
with Q1 as
(
select ConsumerID, Fee, Arrears, Transamount = cast(0 as decimal(18,2)), FeeAllocation = cast(0 as decimal(18,2)), ArrearsAllocation = cast(0 as decimal(18,2)), i = 0
from #Consumer1
union all
select q.ConsumerID,
Fee = cast( Fee - least(q.Fee, t.Transamount) + t.Transamount - least(q.Fee, t.Transamount) - least(q.Arrears, t.Transamount - least(q.Fee, t.Transamount)) as decimal(18,2)),
Arrears = cast( Arrears - least(q.Arrears, t.Transamount - least(q.Fee, t.Transamount)) as decimal(18,2)),
Transamount = cast( t.Transamount as decimal(18,2)),
FeeAllocation = cast( least(q.Fee, t.Transamount) + t.Transamount - least(q.Fee, t.Transamount) - least(q.Arrears, t.Transamount - least(q.Fee, t.Transamount)) as decimal(18,2)),
ArrearsAllocation = cast( least(q.Arrears, t.Transamount - least(q.Fee, t.Transamount)) as decimal(18,2)),
i = i + 1
from Q1 q
inner join #Trans1 t on t.ConsumerID = q.ConsumerID and t.OrdNum = q.i + 1
)
select ConsumerID, Transamount, FeeAllocation, ArrearsAllocation
from Q1 q
where i <> 0
order by ConsumerID, i
option (maxrecursion 0)