Самая большая проблема заключалась в том, что ваше объединение перевернуло таблицы.
DECLARE @Levels TABLE(
ID INT,
ParentID INT,
LevelName VARCHAR(20)
)
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 1 ,0 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 2 ,0 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 4 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 5 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 6 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 7 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 8 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 9 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 18 ,2 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 19 ,18 ,'XXXX'
INSERT INTO @Levels (ID,ParentID,LevelName) SELECT 20 ,19 ,'XXXX'
DECLARE @TargetID INT=20;
WITH cteReports (Id, ParentId, LevelID) AS
(
SELECT Id,
ParentId,
1
FROM @Levels
WHERE Id = @TargetID
UNION ALL
SELECT e.Id,
e.ParentId,
r.LevelID + 1
FROM @Levels e
INNER JOIN cteReports r ON r.ParentId = e.Id
)
SELECT lvl.*
FROM @Levels lvl
INNER JOIN cteReports cte ON cte.ID=lvl.ID
WHERE LevelID = (
SELECT MAX(LevelID) AS MaxLevelID
FROM cteReports
)