I have a table where some parts of the car are connected hierarchically, and I also have the cost of manufacturing these parts in each row. This is a simplification of the table:
parentId Id description qty manufacturingCost costDescripcion
-------- --- ----------- --- ----------------- ---------------
NULL 1 Car 1 100 Assembly the car
NULL 2 Motorcycle 1 100 Assembly the motrocycle
1 11 Wheel 4 20 Assembly the wheel
11 111 Rim 1 50 Manufacture the rim
11 112 Tire 1 60 Manufacture the tire
1 12 Door+Window 4 30 Assembly the door and the window
12 121 Door 1 30 Manufacture the door
12 122 Window 2 10 Manufacture the window
2 11 Wheel 2 15 Assembly the wheel
I need to get all the family tree starting in "Car" and show the total and total costs for each branch. Better explained: the car has 4 wheels, and each wheel has 1 rim and 1 tire, so I have to get 1 car, 4 wheels, 4 tires, 4 wheels. The costs are a bit more complicated: car assembly costs $ 100, but I have to add to this cost, the assembly of 4 wheels (4x20) and the cost of manufacturing 4 wheels (4x50) and 4 tires (4x60), as well as for doors and windows.
This is the expected result:
parentId Id description qty manufacturingCost recLevel
-------- --- ----------- --- ----------------- ---------------
NULL 1 Car 1 940 (100+4*130+4*80) 0
1 11 Wheel 4 130 (20+50+60) 1
1 12 Door+Window 4 80 (30+30+2*10) 1
12 121 Door 4 30 2
12 122 Window 8 10 2
11 111 Rim 4 50 2
11 112 Tire 4 60 2
, , , . . CTE, , , , , ?
:
CREATE TABLE
(
parentId int,
Id int,
description varchar(50),
qty int,
manufacturingCost int,
costDescripcion varchar(150)
)
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
CTE :
with CTE(parentId, id, description, totalQty, manufacturingCost, recLevel)
as
(
select c.parentId, c.id, c.description, c.qty, c.manufacturingCost, 0
from
where c.id = 1
union all
select c.parentId, c.id, c.description, c.qty * ct.totalQty, c.manufacturingCost, ct.recLevel + 1
from
inner join CTE ct on ct.id = c.parentId
)
select * from CTE
, , , ( ):
parentId Id description qty manufacturingCost recLevel
-------- --- ----------- --- ----------------- ---------------
NULL 1 Car 1 100 0
1 11 Wheel 4 20 1
1 12 Door+Window 4 30 1
12 121 Door 4 30 2
12 122 Window 8 10 2
11 111 Rim 4 50 2
11 112 Tire 4 60 2
, , CTE? , ?
,