sql server query - n次迭代后的pivot

时间:2013-02-03 11:17:39

标签: sql sql-server

我有一个包含2列的表格:

'Employee'               'ReportsTo'
1                            
2                            1
3                            1
4                            2
5                            2
6                            3
7                            3
8                            4
9                            4
10                           5

我想这样回来:

'Employee' 'Reporting Officer'
1           2,3,4,5,6,7,8,9,10
2           4,5,8,9,10
3           6,7
4           8,9
5           10
6
7
8
9
10

1 个答案:

答案 0 :(得分:3)

这将适用于您的示例表,但不适用于这样的表(需要更复杂的查询):

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