我遇到的情况是,我需要能够查看给定的人是否在用户/经理层次结构中。 我有下一个表结构: 用户身份 用户名 经理ID
我有2个ID:一些UserId(比如5)和ManagerId(比如2)。因此,我需要知道给定Id(2)的经理是否是给定id(5)的用户的主管?例如,如果
结果SQL查询必须显示对于UserId = 4且ManagerId = 1的答案为真。
我刚创建了获取所有层次结构的查询:
WITH temp (level, UserName, UserId, ManagerId) AS
(
SELECT 1 AS level, EmployeeName, EmployeeId, BossId
FROM Employees
WHERE BossId IS NULL
UNION ALL
SELECT level+1 AS level, EmployeeName, EmployeeId, BossId
FROM Employees, temp
WHERE BossId = UserId
)
SELECT t.* from temp AS t
但现在我不知道如何使用上述条件获得结果查询:(
提前感谢您的帮助!
答案 0 :(得分:3)
在锚点中找到用户,然后沿着层次结构返回。检查针对管理器的递归查询中的行。
如果存在,则返回管理器行。
WITH temp AS
(
SELECT EmployeeName, EmployeeId, BossId
FROM Employees
WHERE EmployeeId = @UserID
UNION ALL
SELECT E.EmployeeName, E.EmployeeId, E.BossId
FROM Employees AS E
inner join temp AS T
ON E.EmployeeId = T.BossId
)
SELECT *
FROM temp
WHERE EmployeeId = @ManagerID
答案 1 :(得分:0)
我已经将所有级别的层次结构包含在CTE中,然后您可以使用它来查询。使用此层次结构,您可以在分隔列中查看给定员工的所有管理员(可能对其他计算有用)。
尝试一下:
WITH cte (UserId, ManagerId, Level, Hierarchy) as (
SELECT EmployeeId, BossId, 0, CAST(EmployeeId as nvarchar)
FROM Employee
WHERE BossId IS NULL
UNION ALL
SELECT EmployeeId, BossId, Level+1,
CAST(cte.Hierarchy + '-' + CAST(EmployeeId as nvarchar) as nvarchar)
FROM Employee INNER JOIN cte ON Employee.BossId=cte.UserId
)
SELECT *
FROM cte
WHERE UserId = 4
AND '-' + Hierarchy LIKE '%-1-%'
这是Fiddle。我使用了UserId = 4和ManagerId = 1。
祝你好运。答案 2 :(得分:0)
如果他或她存在,这将返回BossID:
WITH BOSSES AS
(
SELECT BossID
FROM Employees
WHERE EmployeeID = @uID
UNION ALL
SELECT E.BossID
FROM Employees E
JOIN BOSSES B ON E.EmployeeID = B.BossID
)
SELECT *
FROM BOSSES
WHEN BossID = @bID