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
任何人都可以帮忙吗