Here's an example recursive CTE. Your column child
refers to the name of the current row, and not to it's child. That confused me so I renamed the column from child
to name
.
; with CTE as
(
select name as root
, name
, parent
, val * weightage as change
from test
union all
select parent.root
, child.name
, child.parent
, child.val * child.weightage as change
from CTE parent
join test child
on child.parent = parent.name
)
select root
, sum(change) as val
from CTE
group by
root
This prints:
abcd -30
efgh -100
ijkl 70
mnop 5
qrst 100
uvwx -200
yz -30