I have got one problem as follows:
ID NAME AMOUNT PARENTID
1 Adam 1000 0
2 John 2000 1
3 Clark 1500 2
4 Rita 1200 3
5 jack 1600 3
6 mark 1800 2
7 Finn 1500 6
8 Ryan 1100 6
So the data above is the result of a query with multiple joins and it is a kind of hierarchy or tree something like this:
1
|
2
/ \
3 6
/ \ / \
5 4 7 8
and now I need to modify my query so that I get the following result
ID NAME AMOUNT PARENTID DownstreamSum
1 Adam 1000 0 10700
2 John 2000 1 8700
3 Clark 1500 2 2800
4 Rita 1200 3 0
5 jack 1600 3 0
6 mark 1800 2 2600
7 Finn 1500 6 0
8 Ryan 1100 6 0
So the logic is that the parent should have the sum of all the downstream child nodes in the DownstreamSum column.
for example:
- id 6 should have the sum of amount of id 7 and 8
- id 3 should have the sum of amount of id 4 and 5
but id 2 should have the sum of the amount of id 3 and the sum of amount of id 4 and 5
I tried with many possibilities with partition by and group by but I was not able to get the desired output.