I cleared / fleshed out the mootinator answer a bit and present this code here. I marked this community of answers wiki because the mootinator deserves an answer to the answer. This was the easiest way to present this code without editing its response.
declare @equations table ( OperationID int, EquationID int, Operation char(1), Amount int, [Order] int ) insert into @equations (OperationID, EquationID, Operation, Amount, [Order]) values (1, 1, '+', 12, 1), (2, 1, '+', 12, 2), (3, 2, '/', 2, 3), (4, 2, '+', 12, 1), (5, 2, '-', 2, 2) ;with cteCalc as ( select EquationID, Amount, [Order] from @equations where [Order] = 1 union all select e.equationid, case when e.Operation = '+' then c.Amount + e.Amount when e.Operation = '-' then c.Amount - e.Amount when e.Operation = '*' then c.Amount * e.Amount when e.Operation = '/' then c.Amount / e.Amount end AS Amount, e.[Order] from @equations e inner join cteCalc c on e.EquationID= c.EquationID where e.[Order] = c.[Order] + 1 ), cteMaxOrder as ( select EquationID, MAX([Order]) as MaxOrder from cteCalc group by EquationID ) select c.EquationID, c.Amount from cteMaxOrder mo inner join cteCalc c on mo.EquationID = c.EquationID and mo.MaxOrder = c.[Order] order by c.EquationID option (maxrecursion 1000)
Joe stefanelli
source share