Skip to content
Advertisement

Oracle SQL/PLSQL: Hierarchical recursive query

I have asked very similar questions before but still haven’t achieved the correct result… third times the charm but I now have a stable parent-child relationship to work with.

Every row in the multi-level data set has a cost. For a specific row I need to find the lowest level and roll-up the cost. Then my users will compare the rolled up cost to the row cost and troubleshoot when/if they find differences.

SQL Fiddle here

Data Sample:

I am looking for a function or SQL statement, based on a specific row in the data set (MODEL_NO, MODEL_REV, P_SEQ_NO, SEQ_NO make a unique key) would return the cost roll-up.

For example: Based on this record: 1000, 1, 300, 1100, I would expect a result of: 232.

This is worked out by multiplying the UNIT_COST of each lowest level child by its QTY, adding the sum of each child together, then multiplying the result by the QTY of the parent, repeating the last step until you each the record entered, in this case SEQ_NO = 1100.

Result workings: (22*1 + 4*1 + 3*1 + 1*1 + 28*1) *4

This example is only 1 level deep, my data can go as deep as 6/7 levels.

Advertisement

Answer

I think you need to do this in two steps.

In step 1, you create the hierarchical query results and explode the quantities down to each level. For example, is you have a path like 100->210->320 and the qty values for those are 2, 3, and 5 respectively, then you have exploded quantities 2, 6, and 30, respectively.

Then, having that, you can multiply those exploded quantities by the unit code to get how much that row will contribute to the overall cost of all its parent levels. You can then summarize those costs with a scalar subquery.

Here is the query:

NOTE #1

You did not indicate what the unit_cost represents for rows that are not leaf nodes in the hierarchy. Do they add to the cost of their children somehow? That will change the answer.

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