In this tutorial, I demonstrate a practical application of recursive functions in Power Query to calculate hierarchy levels in organizational structures or MLM systems. Using a custom function with recursion, we can efficiently determine each person’s position in a hierarchical structure based on their referrer relationships, providing valuable insights for organizational analysis and reporting.
Understanding hierarchy levels is essential for visualizing reporting structures, tracking MLM downlines, or mapping any parent-child relationships in your data.
Understanding the Problem: Hierarchy Levels in Organizations
In many organizational structures, particularly in multi-level marketing (MLM) systems or corporate hierarchies, understanding the level depth of each member is crucial. The level represents how many steps a person is from the top of the organization. For instance, in our example, John is at the top (level 0), N is directly below John (level 1), and Thomas is below N (level 2).
Our sample data contains an ID column that uniquely identifies each person and a Referrer column that indicates who brought that person into the organization. The referral relationship establishes the hierarchical structure we need to analyze. Our goal is to calculate each person’s hierarchy level automatically using Power Query’s recursive capabilities.
Setting Up Power Query
To begin working with our data, we need to import it into Power Query where we can create and apply our recursive function:
- Select any cell in your data table
- Go to the Data tab
- Click From Table/Range to import your data into Power Query
This imports your data containing the ID and Referrer columns into the Power Query Editor, where we can start building our solution.
Creating a Recursive Function to Calculate Hierarchy Levels
The core of our solution is a custom function that can call itself (recursion) to track up through the hierarchy until it reaches the top. Here’s how to create it:
- In the Power Query Editor, go to the Home tab
- Click New Source > Other Sources > Blank Query
Now we need to define our function. Our function will require two parameters: the person’s ID we want to calculate the level for and the complete table of people data to reference. The function will:
- Find the row for the current person
- Get their referrer’s ID
- Check if they have a referrer
- If they don’t (they’re at the top), return 0
- If they do have a referrer, call the same function for the referrer and add 1 to the result
The M code for our function looks like this:
(personID, personTable) =>
let
personRow = Table.SelectRows(personTable, each [ID] = personID){0},
personAboveID = personRow[Referrer],
result = if personAboveID = null
then 0
else @HierarchyLevel(personAboveID, personTable) + 1
in
result
Make sure to name your function HierarchyLevel so that the recursive reference to itself works properly. The @ symbol in front of the function name emphasizes that we’re calling the same function again.
Applying the Function to Our Data
After creating our function, we need to apply it to every row in our data table:
- Go back to your main query with the imported data
- Click Add Column > Invoke Custom Function
- Select your HierarchyLevel function
- For personID, select the ID column
- For personTable, we need to reference the current table
When setting the personTable parameter, we initially might try to reference a column name, but this will generate errors. Instead, we need to reference the entire table from the previous step. In Power Query, we can do this by referring to the previous step name.
Once correctly configured, the function will calculate the hierarchy level for each person in our table. Thomas, who is referred by N (ID 2) who in turn is referred by John (ID 1), will show as level 2. John, who has no referrer, will be at level 0.
Testing and Validating the Recursion
To verify our function works correctly, we can examine the calculated levels for each person in our organization:
- John (ID 1): Level 0 (top of hierarchy, no referrer)
- Anne (ID 2): Level 1 (referred by John)
- Thomas (ID 5): Level 2 (referred by Anne)
- Paul: Level 3 (referred by Thomas)
We can further test by changing referrer relationships. For example, if we change Paul’s referrer from Thomas (ID 5) to someone who is already at level 3, Paul would then become level 4. After making such changes in the source data, we can simply refresh our Power Query to see the updated hierarchy levels.
Handling Edge Cases in Your Hierarchy
Our recursive function handles several important edge cases:
- Top-level members (those with null referrers) are assigned level 0
- The function will work for organizations of any depth, continuing to recurse up the chain until it reaches the top
- If the data contains circular references (Person A refers to Person B who refers back to Person A), the recursion could create an infinite loop — consider adding error handling for this scenario in real applications
In a real-world scenario, you might want to enhance this function to handle more complex requirements, such as detecting circular references or processing multiple hierarchies within the same dataset.
Loading the Results Back to Excel
Once you’re satisfied with your hierarchy level calculations:
- In the Power Query Editor, go to Home > Close & Load
- Your data table with the new hierarchy level column will appear in Excel
- Any time your hierarchy changes, simply refresh the query to recalculate all levels
This powerful technique allows you to maintain an up-to-date view of your organizational structure with minimal effort. The recursive approach efficiently handles even large hierarchies without requiring complex formulas or manual tracking.
With this solution in place, you can easily build reports and visualizations that leverage hierarchy level information, enabling better insights into your organizational structure, MLM downlines, or any hierarchical data you’re working with.