gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:08:10 24 4
gpt4 key购买 nike

我为此创建了一个示例 fiddle 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

谁能帮忙解决这个问题

最佳答案

尝试这个。过滤器必须应用于 Anchor query CTE的

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;

FIDDLE DEMO

关于sql - 递归 CTE-查找经理下面的所有员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com