這將您的示例表,但無法正常工作與這樣的表(將需要更復雜的查詢):
Employee ReportsTo
-------- ---------
12 13
13 12
而且它不被稱爲「n次迭代後的透視」。
with cte as (
SELECT 1 Employee,0 ReportsTo UNION ALL
SELECT 2,1 UNION ALL
SELECT 3,1 UNION ALL
SELECT 4,2 UNION ALL
SELECT 5,2 UNION ALL
SELECT 6,3 UNION ALL
SELECT 7,3 UNION ALL
SELECT 8,4 UNION ALL
SELECT 9,4 UNION ALL
SELECT 10,5
),
cte2 as (
SELECT ReportsTo e,Employee ro FROM cte
UNION ALL
SELECT a.e,b.Employee FROM cte2 a JOIN cte b ON a.ro = b.ReportsTo
)
SELECT
Employee,
ISNULL(LEFT(ro,LEN(ro)-1),'') as "Reporting Officer"
FROM (
SELECT
Employee,
REPLACE(REPLACE((
SELECT ro FROM cte2 x WHERE x.e=cte.Employee ORDER BY 1 FOR XML PATH('')
),'<ro>',''),'</ro>',',') ro
FROM cte
) a
sqlfidle
是U確保此行'2 - > 4,5,8,9,10'而不是'2 ---> 4,5'?如果是的話爲什麼你選擇8,9,10 –
這不是主要的。這是一個分層查詢。 –