I have a single table that contains an ID
, Amount
, and Parent_ID
. (It is a little more complex in reality, but this is all the important columns for this example). Basically what i want to do is group and sum the Amount column by the lowest common Parent (ie the ones who's parent id is NULL).
ID Amount Parent_ID
1 100 NULL
2 150 1
3 50 1
4 75 3
5 25 4
6 125 NULL
7 50 6
8 50 7
9 100 8
Expected results:
ID SUM
1 400
6 325
As you can see, it only retuns two records, the ones who dont have a parent, meaning they are top level items. The Sum column is the sum of all of its children's Amount
recursively, so ID
= 1 is the sum of 1,2,3,4 and 5. and ID
= 6 is the sum of 6,7,8, and 9.