这能让你得到你想要的吗?Sqlfiddle 在这里设置: http ://sqlfiddle.com/#!3/9b107/2
; WITH hierarchy_CTE
AS(
SELECT OrganizationID, name, parentid, 1 AS Level
FROM #t1 AS Employee
WHERE OrganizationID = 4
UNION ALL
SELECT boss.OrganizationID, boss.Name, boss.ParentID, Level + 1
FROM #t1 boss
INNER JOIN hierarchy_CTE ON boss.OrganizationID = hierarchy_CTE.parentid
WHERE boss.parentid <> 4 OR boss.parentid IS NULL
)
, hierarchy2_CTE AS
(SELECT cte.Level, cte.name
FROM hierarchy_CTE cte)
SELECT * FROM hierarchy2_CTE
PIVOT
(
MAX(NAME)
FOR Level IN ([1], [2], [3], [4])
) as pvt
改编自 PinalDave 的文章:http: //blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/
这基本上根据给定的员工(在这种情况下,组织 ID 为 4)为您提供一行,并找到他们的命令链。