I took a quick look at your query then noped out because it’s way more complicated that I have time for. But if you are looking for a rolling total you can use windowing functions.
Sum(table.Field) over (partition by Separator1Table.SeparatorField1 , Separator2Table.SeparatorField2 etc. order by Table.FieldtoSortBy)
This will give you a running sum without have to try and use a CTE.
Not sure if that’s what you are looking for, but it seems simpler than whatever you are trying to do.