Thank you @Viorel , @Bruce (SqlWork.com) , LiHongMSFT-4306
I have crafted a recursive query that is performant and no dups. It uses nested Outer Apply.
select a.ID,a.Amount, ChildAmounts.SumAmount2,ChildAmounts.SumAmount3,ChildAmounts.SumAmount4,ChildAmounts.SumAmount5,ChildAmounts.SumAmount6
, ChildAmounts.SumAmount2 +ChildAmounts.SumAmount3+ChildAmounts.SumAmount4+ChildAmounts.SumAmount5+ChildAmounts.SumAmount6 Total_ChildrenAmount
from #ABC a
outer apply
( SELECT SUM(isnull(a2.Amount,0)) SumAmount2, sum(isnull(SumAmount3,0)) SumAmount3, sum(isnull(SumAmount4,0)) SumAmount4, SUM(isnull(SumAmount5,0)) SumAmount5,SUM(isnull(SumAmount6,0)) SumAmount6 FROM #ABC a2 --2
OUTER APPLY ( SELECT SUM(isnull(a3.Amount,0)) AS SumAmount3, sum(isnull(a4.SumAmount4,0)) SumAmount4, SUM(isnull(a4.SumAmount5,0)) SumAmount5 , SUM(isnull(a4.SumAmount6,0)) AS SumAmount6 FROM #ABC a3 --3
OUTER APPLY ( SELECT SUM(isnull(a4.Amount,0))AS SumAmount4 , SUM(isnull(a5.SumAmount5,0)) SumAmount5, SUM(isnull(a5.SumAmount6,0)) AS SumAmount6 FROM #ABC a4 --4
OUTER APPLY ( SELECT SUM(isnull(a5.Amount,0)) AS SumAmount5, SUM(isnull(a6.SumAmount6,0)) AS SumAmount6 FROM #ABC a5 --5
OUTER APPLY ( SELECT SUM(isnull(a6.Amount,0)) AS SumAmount6 FROM #ABC a6 --6
where a6.Childid=a5.id and a6.transtype<>9 and a6.code in ('MX','IN')) a6 --6
where a5.Childid=a4.id and a5.transtype<>9 and a5.code in ('MX','IN')) a5 --5
where a4.Childid=a3.id and a4.transtype<>9 and a4.code in ('MX','IN')) a4 --4
where a3.Childid=a2.id and a3.transtype<>9 and a2.code in ('MX','IN')) a3 --3
where a2.Childid = a.id and a2.code in ('MX','IN') and a2.transtype<>9 --2
) ChildAmounts
where a.ID=1