3

I have a situation where I need to be able to see if a given person is within a user/manager hierarchy. I have the next structure of table: UserId UserName ManagerId

I have 2 IDs: some UserId (say 5) and ManagerId (say 2). As a result I need to know if manager with given Id (2) is chief for user with given id (5)? For example, if

  1. User 1 reports to user 2.
  2. User 3 reports to user 1.
  3. User 4 reports to user 3

the result SQL-query have to show that for UserId = 4 and ManagerId = 1 answer is true.

I've just created query for getting all hierarchy:

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

But now I don't know how to get result query with above mentioned conditions :(

Thanks in advance for any help!

4

3 回答 3

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
于 2013-02-02T21:52:49.473 回答
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
于 2013-02-02T22:16:54.607 回答
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-%' 

这是小提琴。我使用了 UserId = 4 和 ManagerId = 1。

祝你好运。

于 2013-02-02T22:03:54.110 回答