CTE显示org char层次结构?

时间:2016-05-24 21:42:31

标签: sql-server common-table-expression

尝试执行递归CTE以显示我在下面的表中的组织字符串层次结构,有点难以接受帮助。

DECLARE @Org TABLE(
    EmployeeID smallint NOT NULL
   ,ManagerID smallint NULL
   ,LoginName varchar(50)
);

INSERT @Org 
VALUES (1,null,'Peter'),(2,1,'Larry'),(3,1,'John'),
       (4,1,'Lisa'),    (5,2,'Linda'),(6,3,'Nathan'),
       (7,3,'Tom') ,    (8,3,'Terry'),(9,4,'Lou'),
       (10,7,'David'),  (11,9,'Ken') ,(12,9,'Robert');

试图让它看起来像

EmployeeID    LoginName ManagerID LEVEL
    1           Peter       NULL    0
    2           Larry       1       1
    3           John        1       1
    4           Lisa        1       1
    9           Lou         4       2
    6           Nathan      3       2
    7           Tom         3       2
    8           Terry       3       2
    5           Linda       2       2
    10          David       7       3
    11          Ken         9       3
    12          Robert      9       3

1 个答案:

答案 0 :(得分:1)

<强>查询

;with CTE as
(
  select  EmployeeID
         ,ManagerID
         ,LoginName
         ,0 as Level
  from @Org Where ManagerID IS NULL

  union all

  select  T.EmployeeID
         ,T.ManagerID
         ,T.LoginName
         ,C.Level + 1
  from @Org as T
    inner join CTE C  
      on T.ManagerID = C.EmployeeID
)
select *
from CTE
Order by EmployeeID

结果集

╔════════════╦═══════════╦═══════════╦═══════╗
║ EmployeeID ║ ManagerID ║ LoginName ║ Level ║
╠════════════╬═══════════╬═══════════╬═══════╣
║          1 ║ NULL      ║ Peter     ║     0 ║
║          2 ║ 1         ║ Larry     ║     1 ║
║          3 ║ 1         ║ John      ║     1 ║
║          4 ║ 1         ║ Lisa      ║     1 ║
║          5 ║ 2         ║ Linda     ║     2 ║
║          6 ║ 3         ║ Nathan    ║     2 ║
║          7 ║ 3         ║ Tom       ║     2 ║
║          8 ║ 3         ║ Terry     ║     2 ║
║          9 ║ 4         ║ Lou       ║     2 ║
║         10 ║ 7         ║ David     ║     3 ║
║         11 ║ 9         ║ Ken       ║     3 ║
║         12 ║ 9         ║ Robert    ║     3 ║
╚════════════╩═══════════╩═══════════╩═══════╝