我有一个地方汽车的某些部分是分层相关的表,我也有在列的每一个制造这些零部件的成本。 这是表的简化:
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
我需要得到整个家族树首发于“汽车”,并显示总数量和每个分支的总成本。 更好地解释:有车有4个车轮并且每个车轮都有1轮辋和轮胎1,所以我应该得到1台车,4个轮子,4个轮胎,轮辋4。 一点点的费用更复杂:组装汽车的成本$ 100,但是我要补充到这个成本,装配4个轮子(4×20),并制造4轮辋(4×50)的成本之一,并在4个轮胎(4x60),与同为门窗。
这是预期的结果:
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
我可以很容易地达到这个一个使用递归函数或存储过程,但它是更复杂的结构非常缓慢,所以我尝试使用公用表表达式来做到这一点。 但我didn't发现总结成本的方式。 我使用递归CTE开始在顶层和下降,我也得到了量的总和,但我应该从内到外的结构来总结的费用,我该怎么办呢?
这是创建表的代码:
CREATE TABLE #Costs
(
parentId int,
Id int,
description varchar(50),
qty int,
manufacturingCost int,
costDescripcion varchar(150)
)
INSERT INTO #Costs VALUES (NULL , 1, 'Car', 1, 100, 'Assembly the car')
INSERT INTO #Costs VALUES (NULL , 2, 'Motorcycle', 1, 100, 'Assembly the motrocycle')
INSERT INTO #Costs VALUES (1 , 11, 'Wheel', 4, 20, 'Assembly the wheel')
INSERT INTO #Costs VALUES (11 , 111, 'Rim', 1, 50, 'Manufacture the rim')
INSERT INTO #Costs VALUES (11 , 112, 'Tire', 1, 60, 'Manufacture the tire')
INSERT INTO #Costs VALUES (1 , 12, 'Door+Window', 4, 30, 'Assembly the door and the window')
INSERT INTO #Costs VALUES (12 , 121, 'Door', 1, 30, 'Manufacture the door')
INSERT INTO #Costs VALUES (12 , 122, 'Window', 2, 10, 'Manufacture the window')
INSERT INTO #Costs VALUES (2 , 11, 'Wheel', 2, 15, 'Assembly the wheel')
这是我写的CTE:
with CTE(parentId, id, description, totalQty, manufacturingCost, recLevel)
as
(
select c.parentId, c.id, c.description, c.qty, c.manufacturingCost, 0
from #Costs c
where c.id = 1
union all
select c.parentId, c.id, c.description, c.qty * ct.totalQty, c.manufacturingCost, ct.recLevel + 1
from #Costs c
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? 如果是这样,我该怎么办呢?
非常感谢你,
Antuan