Given the following tree structure in a SQL table, and assuming the data is consistent (there are no rows with the same name, but different parents):
| name | parent | value |
|------|--------|-------|
| a | null | 10 |
| b | a | 15 |
| b | a | 4 |
| c | a | 15 |
| d | a | 10 |
| e | b | 5 |
| f | b | 5 |
| g | null | 20 |
I am looking for a query to sum up all sub-categories of a given node, like this:
| name | parent | value |
|------|--------|-------|
| a | null | 64 |
| b | a | 29 |
| c | a | 15 |
| d | a | 10 |
| e | b | 5 |
| f | b | 5 |
| g | null | 20 |
So, I can make only the first level of summation, and I can think of joining this to table itself on parent and and sum again... but I am looking for a solution for trees of unspecified depth. For the level 1 I have for example:
SELECT
NAME,
PARENT,
SUM(VALUE) AS VALUE
FROM
TEST
GROUP BY
NAME,
PARENT
ORDER BY
NAME ASC;
Aman GuptaPosted Sep 24, 2024, 6:51 AM
Hi Ravi,
To handle aggregation over a hierarchical structure (tree) in SQL where the depth of the tree is unspecified, you can use a recursive common table expression (CTE). This will allow you to aggregate values across all descendants of a given node, regardless of the depth of the tree.
SQL Query Explanation:
We will use a recursive CTE to navigate the hierarchy, starting from the root node (parent IS NULL) and traversing all the child nodes, summing up the value for each node and its descendants.
Here is the query that can achieve this:
Recursive Query:
Key Points:
Anchor Member: This is the base case for the recursion. We start by selecting the top-level nodes (where
parent IS NULL).Recursive Member: In this part, we join the CTE (
RecursiveSum) with the original table (test) to find the child nodes for each parent. We recursively sum the values as we traverse down the tree.Final Aggregation: After recursion, we sum the
valuefield for each node, grouping bynameandparentto get the total value of each node and all its descendants.Expected Output:
The query will return the sum of values for each node, including its descendants. Based on your input data, the output will look something like this:
a: Includes its own value (10) plus all its descendants (b, c, d, e, f), resulting in a total of 64.
b: Includes its own value (sum of 15 and 4) plus its descendants (e and f), resulting in 29.
g: Has no descendants, so its total value remains 20.
This approach allows for aggregation across a hierarchy of unspecified depth, and can handle multiple levels of tree depth.
Mohammad HussainPosted Sep 23, 2024, 3:12 PM
Please try this
Tahir AnsariPosted Sep 22, 2024, 2:16 PM
try this CTE