Skip to content
Advertisement

Using CTE to determine a specific Hierarchical ID for Family Members

I’m trying to figure out how to attach an incrementing ID to my resultset while using CTE.

My table has data like so:

I want to add a column called RelationId. Basically the “F” person will always get “1”, The relation “S” will always get “2” and any subsequent “C” relation will get 3,4,5…etc

They are linked by the ParentLinkId so ParentLinkId = PersonId.

I tried to use CTE to recursively increment this value but I keep getting stuck on an infinite loop

I tried :

This is the result I keep on getting:

It should be

I think I’m getting close using CTE but any help or prod in the right direction would be greatly appreciated!

Advertisement

Answer

This sounds like a simple row_number():

Here is a db<>fiddle.

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