The typical example for e.g. summing a whole tree in PostgreSQL is using WITH RECURSIVE (Common Table Expressions). However, these examples typically go from top to bottom, flatten the tree and perform an aggregate function on the whole result set. I have not found a suitable example (on StackOverflow, Google, etc.) for the problem I am trying to solve:
Consider an unbalanced tree where each node can have an associated value. Most of the values are attached to leaf nodes, but the others may have values as well. If a node (leaf or not) has an explicitly attached value, this value can be directly used without further calculation (subtree can be ignored, then). If the node has no value, the value should be computed as the average of its direct children.
However, as none of the nodes are guaranteed to have a value attached, I need to go bottom up in order to obtain a total average. In a nutshell, starting from the leafs, I need to apply AVG()
to each set of siblings and use this (intermediate) result as value for the parent node (if it has none). This parent's (new) value (explicitly attached, or the average of its children) is in turn used in the calculation of average values at the next level (the average value of the parent and its siblings).
Example situation:
A
+- B (6)
+- C
+- D
+- E (10)
+- F (2)
+- H (18)
+- I (102)
+- J (301)
I need to compute the average value for A, which should be 10
(because (6+6+18)/3 = 10
and I
,J
are ignored).
Your data can be stored as:
The simplest way to do bottom-up aggregation is a recursive function.
Test it here.
It is possible to achieve the same in an sql function. The function code is not so obvious but it may be a bit faster than plpgsql.
Viewing a tree from the bottom up using cte is not especially complicated. In this particular case the difficulty lies in the fact that average should be computed for each level separately.
Test it here.