小编典典

递归CTE-查找经理以下的所有员工

sql

我为此SQLFIDDLE创建了一个样本小提琴

CREATE TABLE [dbo].[Users](
    [userId] [int] ,
    [userName] [varchar](50) ,
    [managerId] [int] ,
   )

INSERT INTO dbo.Users
    ([userId], [userName], [managerId])
VALUES
(1,'Darry',NULL),
(2,'Cono',1),
(3,'Abros',2),
(4,'Natesh',1),
(5,'Ani',3),
(6,'Raju',5),
(7,'Pinky',5),
(8,'Miya',4)

我的要求就像在该特定经理下方显示所有员工层次结构

这是我尝试过的

WITH UserCTE AS (
  SELECT userId, userName, managerId, 0 AS EmpLevel
  FROM Users where managerId IS NULL

  UNION ALL

  SELECT usr.userId, usr.userName, usr.managerId, mgr.[EmpLevel]+1
  FROM Users AS usr
    INNER JOIN UserCTE AS mgr
      ON usr.managerId = mgr.userId where usr.managerId IS NOT NULL
)
SELECT * 
  FROM UserCTE AS u where u.ManagerId=3
  ORDER BY EmpLevel;

输出 :

userName
--------
    Ani

我期望的输出是,如果我给出ManagerId 3,则应显示以下员工

1.Abros
2.Ani
3.Raju
4.Pinky

任何人都可以帮忙吗


阅读 153

收藏
2021-04-14

共1个答案

小编典典

试试这个。必须在Anchor queryCTE中应用过滤器

WITH UserCTE
     AS (SELECT userId,
                userName,
                managerId,
                0 AS EmpLevel
         FROM   [Users]
         WHERE  managerId = 3
         UNION ALL
         SELECT usr.userId,
                usr.userName,
                usr.managerId,
                mgr.[EmpLevel] + 1
         FROM   [Users] AS usr
                INNER JOIN UserCTE AS mgr
                        ON usr.managerId = mgr.userId
         WHERE  usr.managerId IS NOT NULL)
SELECT *
FROM   UserCTE AS u
ORDER  BY EmpLevel;
2021-04-14