Forum Discussion
Determine level within multi level parent child hierarchy
Hi joshua1990
In the query, add a custom column that calculates the level for each parent-child combination by calling a recursive function. The recursive function will take the current parent-child combination as input and check if the parent is also present in the child column. If so, it will call itself with the new parent-child combination, and increment the level by . Otherwise, it will return the current level.
You can define the function like this:
let
hierarchy = [Parent = "1", Child = "A1", Quantity = 1],
level = 1,
findLevel = (hierarchy, level) =>
let
parent = hierarchy[Parent],
child = hierarchy[Child],
newHierarchy = Table.SelectRows(hierarchy, each [Parent] = child),
newLevel = level + 1
in
if List.Count(newHierarchy) = 0 then
level
else
findLevel(newHierarchy{0}, newLevel)
in
findLevel(hierarchy, level)
Then you can use this function in a custom column, you can call this function by passing the current row to it, and use the result in a custom column.
= Table.AddColumn(hierarchy, "Level", each findLevel([Parent = [Parent], Child = [Child]], 1))
Finally, you can expand the new column to have it in your table.
Please note, this example is based on the assumption that you have only one Parent-child combination in the table. If there are multiple parent-child combinations, you need to iterate over the table rows, and call the function for each row.
Please let me know if this helps or if you have any other questions.
- joshua19903 years agoPost Prodigy
nitishsh91 : Thanks a lot! Since it is multi level, how would you iterate this per row? I don't get it.
- joshua19903 years agoPost Prodigy
nitishsh91 : ANy idea?
- nitishsh913 years agoSolution Supplier
The function will take parent n child as input n it will have to be added as a new column to give desired result, I believe it should work though still need to try it myself as I have visualised it conceptually the way an algorithm works.
I will try this in detail sometime tomorrow n let you know as I couldn't find time to work out this solution n had marked it for further analysis.