I have hierarchical data (right) in table in following manner which creates Hierarchy as shown in left. Tables are kept in oracle 11g.
TREE Hierarchy Tree Table
-------------- Element Parent
------ ------
P0 P0
P1 P1 P0
P11 P2 P0
C111 P11 P1
C112 P12 P1
P12 P21 P2
C121 P22 P2
C122 C111 P11
P2 C112 P11
P21 C121 P12
C211 C122 P12
C212 C211 P21
P22 C212 P21
C221 C221 P22
C222 C222 P22
My data table has values as follows. It contains values for all leaf nodes.
Data Table
Element Value C111 3 C112 3 C121 3 C122 3 C211 3 C212 3 C221 3 C222 3 P11 6
I need to generate insert statement, preferably single insert statement which will insert rows in data table based on sum of values of the children.
Please note we need to calculate sum for only those parents whose value is not present in data table.
Data Table (Expected After Insert)
Element Value C111 3 C112 3 C121 3 C122 3 C211 3 C212 3 C221 3 C222 3 P11 6 -- Rows to insert P12 6 P21 6 P22 6 P1 12 P2 12 P0 24
If all leaf nodes are at the same height (here lvl=4), you can write a simple CONNECT BY query with a ROLLUP:
The insert would look like:
If the height of the leaf nodes is unknown/unbounded this gets more hairy. The above approach wouldn’t work since ROLLUP needs to know exactly how many columns are to be considered.
In that case, you could use the tree structure in a self-join :