Skip to content
Advertisement

Query with hierarchical structure and variable number of hierarchy levels

I have table ‘Areas’ containing customer’s areas:

Areas are organized in hierarchy up to four levels using PARENT_ID pointing to parent’s AREA_ID. PARENT_ID for top level Area IS NULL.

Table of ‘Customers’ hase AREA_ID referencing the lowest level of area hierarchy:

I want to get the result table like this:

The problem here is that customer’s area (AREA_ID) does not allways point to the lowest fourth level of areas. Sometimes it points to fourth level AREA_ID, sometimes third and so on.

Depending of area levels, the resulting table should look like:

I don’t know how to make this recursion with variable number of levels inside single SQL query. I need just single SQL query (not procedure with cursor passing the recursion loop).

Advertisement

Answer

You need a recursive CTE that returns all the levels for each area which will be joined to customers:

See the demo.
Results:

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