Parent-Child Hierarchy w/ multiple parents

Dear community,

there are several solutions for parent/child hierarchy topics if a child has only one possible parent.
I have a dataset w/ two columns “parent” and “child”.
A “child” can have several “parents” and also several more “children”.
Is there a solution to get the top “parents” and all “children” w/ the respective level?

example data
parent | child
A | B
B | C
B | D
B | E

Z | B
B | C
B | D
B | E

Y | C
Y | D
Y | E

needed result

Top parent | child | level
A | B | 1
A | C | 2
A | D | 2
A | E | 2

Z | B | 1
Z | C | 2
Z | D | 2
Z | E | 2

Y | C | 1
Y | D | 1
Y | E | 1

Hi @christian_kopp , this should be possible using a recursive loop.

Having first established all the “top level” parents, which can be done by finding those parents which do not appear in the “child” column, it is possible to “walk” the hierarchy.
On each iteration, we find the child-of-current-child for each top level parent, until there is nothing left to find

Here is an example implementation which | think does what you are looking for, but please be sure to test it for your actual data, in case there are unforeseen edge cases.

1 Like

Hi @takbb , that works perfect, thank you very much for the fast solution and have a great day.

1 Like

Hi @christian_kopp , glad to hear it worked for you and thank you for marking the solution.