I have a SQL table where the rows in the table have a parent-child relationship with each other. I would like to write a recursive SQL query to find the oldest ancestor for each of these rows (or the row itself if it has no parent). So in other words, if my table looks like this:
Child | Parent |
---|---|
1 | null |
2 | 1 |
3 | 2 |
4 | null |
5 | 4 |
6 | null |
7 | null |
8 | 3 |
9 | 5 |
Then my final output should be:
Child | OldestAncestor |
---|---|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 4 |
5 | 4 |
6 | 6 |
7 | 7 |
8 | 1 |
9 | 4 |
Can this be done? I know how to use recursive SQL to find an individual parent-child relationship, I'm just not sure if that can be taken a step further to find the parent's parent, etc.