我有一张表,其中汽车的某些零件按层次结构相关,并且每一行中还有制造这些零件的成本。这是该表的简化:
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 个车轮 (4x20) 的成本以及制造 4 个轮辋 (4x50) 和 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
我可以使用递归函数或存储过程轻松实现这一目标,但对于更复杂的结构来说它非常慢,因此我尝试使用通用表表达式来实现这一点。但我没有找到计算成本的方法。我使用从顶层开始向下的递归 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