I have the following data (a sample of real data, which is much bigger):
id p_id
1 null
2 1
3 1
4 2
5 4
6 5
7 5
8 3
9 7
Would it be possible to use analytic function of SQL Server to get the following result (get the deepest hierarchy):
id p_id
1 null
2 1
4 2
5 4
7 5
9 7
I can use Recursive CTE to get the level of each ID, however I'm trying to use analytic functions instead. I suspect I need to use Lag or Lead function, however I am new to analytic functions so if this is possible to be done, please help share the solution. Your help is appreciated! Thanks.