Hi @Anant ,
Welcome to Microsoft Q&A!
You could have a try with Recursive CTE.
Please refer to below and check whether it is helpful.
;with HierarchyLvl as
(
SELECT [Employee_ID]
,[Manager_ID]
,[Title]
,1 as Level
FROM [dbo].yourtable
where [Manager_ID] is null
UNION ALL
SELECT e.[Employee_ID]
,e.[Manager_ID]
,e.[Title]
,Level + 1
FROM [dbo].yourtable e INNER JOIN HierarchyLvl d on e.[Manager_ID] = d.[Employee_ID]
)
select * into #tempHierarchyLvl
from HierarchyLvl
Query1:
select [Employee_ID] from #tempHierarchyLvl
where level=1
Output:
Employee_ID
A101
Query2
select [Employee_ID] from #tempHierarchyLvl
where level=2
Output:
Employee_ID
A102
A103
A104
Query3
select [Employee_ID] from #tempHierarchyLvl
where Manager_ID in (
select [Employee_ID] from #tempHierarchyLvl
where level=2)
Output:
Employee_ID
A401
A402
A301
A302
A201
A202
Or you could combine them into one row like below:
select a.Employee_ID,a.Manager_ID,f.Employee_ID level1,e.Employee_ID level2,d.Employee_ID level3,c.Employee_ID level4,b.Employee_ID level5
from yourtable a
left join yourtable b on a.Manager_ID=b.Employee_ID
left join yourtable c on b.Manager_ID=c.Employee_ID
left join yourtable d on c.Manager_ID=d.Employee_ID
left join yourtable e on d.Manager_ID=e.Employee_ID
left join yourtable f on e.Manager_ID=f.Employee_ID
where a.Employee_ID='A701'
Output:
Employee_ID Manager_ID level1 level2 level3 level4 level5
A701 A601 A101 A102 A201 A501 A601
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.