Skip to content
Advertisement

How to SUM all subchildren tree in SQL recursively?

Good day, I’ve been pulling my hair on this problem for a while ><“

I have 4 categories in a tree structure.

tenant_category_transaction_view:

enter image description here

I would like to have the sum of all children “sumSubtotal” on every category

Something like that: enter image description here

I’ve managed to come very close… But there’s something I don’t get ><“

Result of the above query:

enter image description here

It seems I’m generating the correct treeSum but upside down in only one branch

Would you be so kind to give me a hand?

Thank you for your time 🙂

Advertisement

Answer

I’ve updated the fiddle to include the exact schema / data provided in the question, including the null issues. It also includes an example of my suggested changes.

The solution basically takes the given data and transforms it internally (in the CTE term nodes) so that the 2 top level category rows link to a common row, with id 0, so that the original logic I provided can be used to treat this as one hierarchical list of categories.

First, we find all the branch lists recursively. Each branch is identified by a corresponding root. Then, we aggregate the node quantities for each root/branch.

The fiddle

The result:

root idParentCategory sumSubtotal sumQuantity total
0 null 0 0 9890
1 0 9800 98 9800
4 0 20 1 90
5 4 30 1 70
6 5 40 1 40

The setup:

The following uses a suggested slight adjustment to the original table and data. Instead of the 2 top null parent references for rows with id 1 and 4, add a top row (with id 99, for instance) and let rows with id 1 and 4 refer to that with parent = 99.

The result:

root idParentCategory sumSubtotal sumQuantity total
99 null 0 0 9890
1 99 9800 98 9800
4 99 20 1 90
5 4 30 1 70
6 5 40 1 40

Additionally, this can be written to aggregate based on t2.id, which is the primary key, allowing slight simplification, due to functional dependence.

Finally, we can remove the last JOIN by carrying other root values within the recursive logic:

The setup:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement