I have an interesting SQL problem. I have a hierarchic table of parts that make a bill of material. similar to this:
ASSEMBLY
---------
parent_part_id
part_id
quantity
I get the hierarchy of this structure with a query like this:
SELECT level, part_id, quantity
from assembly
start with parent_part_id = 1
connect by parent_part_id = prior part_id;
the output might look like this:
level part_id quantity
----- ------- ---------
1 2 2
2 3 10
1 4 2
2 5 1
3 3 5
so far so good.
the question is this: how do I calculate the total number of each part required in order to make the top level assembly (part 1)?
Grouping this result set by part and summing the quantity is not correct, since the quantity should be multiplied by the quantity of the part immediately above the current part in the hierarchy, recursively up the tree.
I am thinking this is a LAG function, but having trouble visualizing it.
edit: expected results:
part_id quantity
------- --------
2 2
3 30
4 2
5 2
more edit: i get interesting results with this query
SELECT rownum, level lvl, part_id, quantity, unit_of_measure
, connect_by_isleaf || sys_connect_by_path(quantity,'*') math
from assembly
start with parent_part_id = 1
connect by parent_part_id = prior part_id
the math column returns a string representation of the calculation i want to perform 🙂 for instance it may say:
1*1*2*10
or something similar and appropriate… perhaps making a function to parse this and return the result will solve the problem.. anyone think this is outrageous?
In Oracle 11 R2 its possible with a
common table expression:The test data:
The select statement:
Edit Prior to Ora11R2, it might work with a
model clause:Edit II Another possibility would be to sum the logarithms of quantity and then take the sum’s exponent: