I have a table like this:
| COMPOSANT | COMPOSE | QTE | PA | COST | LEVEL |
|---|---|---|---|---|---|
| PARENT1 | CHILD1 | 24 | 0 | ||
| PARENT1 | CHILD2 | 2 | 0 | ||
| CHILD1 | CHILD11 | 10 | 1 | ||
| CHILD1 | CHILD12 | 4 | 3 | 12 | 1 |
| CHILD11 | CHILD111 | 100 | 1 | 100 | 2 |
| CHILD2 | CHILD21 | 5 | 10 | 50 | 1 |
And I try to make a query to sum all children costs to parents
DECLARE @tmp TABLE ( [COMPOSANT] [varchar](25) NULL, [COMPOSE] [varchar](25) NULL, [QTE] [numeric](38, 9) NULL, [PA] [numeric](38, 9) NULL, [COST] [numeric](38, 9) NULL, [LEVEL] [int] NULL ) INSERT INTO @tmp VALUES ('PARENT1', 'CHILD1', 24, NULL, NULL, 0); INSERT INTO @tmp VALUES ('PARENT1', 'CHILD2', 2, NULL, NULL, 0); INSERT INTO @tmp VALUES ('CHILD1', 'CHILD11', 10, NULL, NULL, 1); INSERT INTO @tmp VALUES ('CHILD2', 'CHILD21', 4, 3, 12, 1); INSERT INTO @tmp VALUES ('CHILD11', 'CHILD111', 100, 1, 100, 2); SELECT * FROM @tmp My expected result is something like this:
| COMPOSANT | COMPOSE | QTE | PA | COST | LEVEL |
|---|---|---|---|---|---|
| PARENT1 | CHILD1 | 24 | 1012 | 24288 | 0 |
| PARENT1 | CHILD2 | 2 | 50 | 100 | 0 |
| CHILD1 | CHILD11 | 10 | 100 | 1000 | 1 |
| CHILD1 | CHILD12 | 4 | 3 | 12 | 1 |
| CHILD2 | CHILD21 | 5 | 10 | 50 | 1 |
| CHILD11 | CHILD111 | 100 | 1 | 100 | 2 |
And so TOTAL COST is 24288+100
I tried using a recursive CTE without success.
Here are my tests :
WITH CTE_HIERARCHIE AS ( -- Feuilles avec PA connus SELECT COMPOSE AS COMPOSE, COMPOSANT, QTE, PA, cast(PA * QTE as [numeric](38, 9)) AS COST, 0 AS INVLEVEL ,LEVEL FROM @tmp WHERE PA IS NOT NULL UNION ALL -- Propagation vers les parents SELECT parent.COMPOSE AS COMPOSE, parent.COMPOSANT, parent.QTE, cast(child.COST as numeric (38, 9)) as PA, cast( child.PA*child.QTE as [numeric](38, 9)) AS COST, child.INVLEVEL + 1,parent.LEVEL FROM @tmp parent INNER JOIN CTE_HIERARCHIE child ON parent.COMPOSE = child.COMPOSANT ) -- Résumé des coûts par composant parent SELECT COMPOSANT,COMPOSE,QTE,SUM(PA) as PA, SUM(COST) as COST,LEVEL FROM CTE_HIERARCHIE GROUP BY COMPOSANT,COMPOSE,LEVEL,QTE ORDER BY LEVEL,COMPOSANT,COMPOSE; But some cost are wrong I on level 0 and 1. I don't know how to solve this.
Here some more about how it works:

1000in the data. Post the code and logic in the question itself. The total cost should be 162.