SQL recursive assembly bom cost calculation

Fan, Allan 21 Reputation points
2022-06-24T02:58:15.74+00:00

We need to expand a recursive BOM to summarize all raw material costs to check whether the standard cost setting is correct. The BOM structure is as follows:
214612-bom.png

The expected output is as follows:
214535-result.png

Can somebody please help to show how to get the output?
Thanks a lot!

Developer technologies | Transact-SQL
{count} votes

Accepted answer
  1. LiHong-MSFT 10,056 Reputation points
    2022-06-24T07:06:48.897+00:00

    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:
    214630-image.png

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.