Hi @Fan, Allan
Is there a column like 'Parent_Level' in your initial table?
If so, then check this query:
CREATE TABLE #Test (Parent VARCHAR(10),[Level] INT,ParentCost INT,Child VARCHAR(10),Quantity INT,ChildCost INT)
INSERT INTO #Test VALUES
('A',1,66,'B',1,52),('A',1,66,'C',2,2),('A',1,66,'D',3,2),
('B',2,52,'B1',2,18),('B',2,52,'B2',2,2),('B',2,52,'B3',2,3),
('B1',3,18,'B11',2,4),('B1',3,18,'B12',3,2)
--SELECT * FROM #Test
;WITH CTE AS
(
SELECT t1.Parent,t1.ParentCost, t1.Child, t1.level, t1.ChildCost * t1.Quantity AS total
FROM #Test t1 LEFT JOIN #Test t2 ON t2.Parent = t1.Child AND t2.level = t1.level + 1
WHERE t2.Child IS NULL
UNION ALL
SELECT t1.Parent,t1.ParentCost, t1.Child, t1.level, (total * t1.Quantity) as total
FROM #Test t1 INNER JOIN CTE ON CTE.Parent = t1.Child AND CTE.level = t1.level + 1
)
SELECT Parent,ParentCost,SUM(total) AS Total_cost
FROM CTE
GROUP BY parent,ParentCost
Output:
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.