Check an adjusted query for new details:
declare @temp table ( parent varchar(max), part varchar(max), level int, cost money, qty int, top_nod varchar(max))
insert @temp values
('P1','P2',1,1,1,'P1'),
('P1','S1',1,1,6,'P1'),
('P1','P3',1,3,12,'P1'),
('P2','S2',2,1,5,'P1'),
('P2','S3',2,2,2,'P1'),
('P2','P4',2,3,4,'P1'),
('P4','S2',3,10,2,'P1'),
('P4','S3',3,20,3,'P1'),
('P4','P5',3,30,4,'P1'),
('A1','Q2',1,5,2,'A1'),
('A1','S1',1,20,4,'A1'),
('A1','S2',1,15,5,'A1'),
('Q2','R1',2,10,7,'A1'),
('Q2','S3',2,3,1,'A1'),
('R1','S4',3,4,2,'A1'),
('R1','S5',3,5,5,'A1'),
('R1','S6',3,7,2,'A1')
select * from @temp
;
with Q as
(
select parent, part, level, cost, qty, top_nod
from @temp
union all
select t.parent, Q.part, t.level, Q.cost, Q.qty * t.qty, Q.top_nod
from @temp t
inner join Q on Q.parent = t.part and Q.level = t.level + 1 and Q.top_nod = t.top_nod
)
select parent, sum(cost * qty) as final_cost
from Q
where parent = top_nod
group by parent
order by parent
Results:
/*
parent final_cost
A1 969,00
P1 864,00
*/
P4 at level 3 has S2,S3 and P5 as child. So sum(cost*qty) for P4 at level 3 is $200.