TSQL中的递归ManagerAssociate查询。

问题描述 投票:0回答:1

以此为例 联系

我希望能够通过一个人力资源表,在表中填写正在查找自己的经理和他们的报告(这表明他们也是什么级别)。

数据。

    AssociateID     AssociateName    ManagerID    AssociateTitle
    ===========     =============    =========    ==============
    1               Jack Frost                    Chief Executive Officer
    2               Cindy Smith      1            President of Sales
    3               William Howard   1            President of Technology
    4               Ben Samson       2            Director of Tradeshow
    5               Sarah Jones      2            Director of Documentation
    6               Laurie Ralph     4            Manager
    7               Tina Nelson      5            Manager
    8               Joe May          6            Coordinator
    9               Peter Gill       7            Coordinator
   10               Kelly Kraft      2            Director of Facilities
   11               Heidi Trump      8            Administrative Assistant

如果CEO签到,他将得到以下数据:

Jack Frost
 Cindy Smith
  Ben Samson
   Laurie Ralph
    Joe May
     Heidi Trump
 William Howard

但如果辛迪-史密斯签到,她的名单就会是:

 Cindy Smith
  Ben Samson
   Laurie Ralph
    Joe May
     Heidi Trump

缩进是为了让人看清楚. 我还在想,是否可以有一列显示下面的人是什么级别。 1级;2级;等等

而如果一个签到的人(例如:海蒂-特朗普)她的名单只有她的名字。

这在TSQL中可以实现吗?

tsql recursive-query
1个回答
0
投票

我有它,并希望分享。

DECLARE @Associate float 
Set @Associate = 1

;
WITH DirectReports(ManagerID, EmployeeID, Associate, Title, EmployeeLevel) AS   
(  
    SELECT ManagerID, AssociateID, LegalLastName + ', ' + LegalFirstName, Title, 1 AS EmployeeLevel  
    FROM AssociateMaster 
    WHERE 
        ManagerID = @Associate

    UNION ALL  

    SELECT e.ManagerID, e.AssociateID, e.LegalLastName + ', ' + e.LegalFirstName, e.Title, EmployeeLevel + 1  
    FROM dbo.AssociateMaster AS e  
        INNER JOIN DirectReports AS d  
        ON e.ManagerID = d.EmployeeID  
)  

SELECT 
  DR.ManagerID, MGR.LegalLastName + ', ' + MGR.LegalFirstName AS AssociateName, DR.EmployeeID, DR.Associate, DR.Title, DR.EmployeeLevel   
FROM DirectReports DR
  INNER JOIN AssociateMaster as Mgr ON DR.ManagerID = Mgr.AssociateID

UNION

SELECT ' ', ' ', AssociateID, LegalLastName + ', ' + LegalFirstName, Title, 0  
FROM AssociateMaster 
WHERE 
    AssociateID = @Associate

ORDER BY 
  DR.EmployeeLevel Asc, 
  MGR.LegalLastName + ', ' + MGR.LegalFirstName ASC,
  DR.Associate Asc

OPTION (MAXRECURSION 0);
© www.soinside.com 2019 - 2024. All rights reserved.