Skip to content
Advertisement

Table recursive lookup on itself

I have the following table below.

I want to select all of the members of Group-D

However, Group-D also contains Group-C along with User 5. Group-C contains Group-A and Group-B.

So, the select should return:

Obviously, without doing multiple lookups on itself, I will not get that output.

How can I make the select statement do a table lookup within itself like that?

grp member
Group-A User-1
Group-A User-2
Group-B User-3
Group-B User-4
Group-C Group-A
Group-C Group-B
Group-D Group-C
Group-D User-5
Group-E User-6

Advertisement

Answer

The following recursive CTE will traverse through the data to arrive at parent/child relationships:

result

See this working at db<>fiddle

Note, I introduced “lvl” as a way to implement an “escape” from the recursion – “just in case”

Also, if you don’t want to include the top level item in the result, use

and you could commence lvl as zero instead of 1 in the CTE

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