微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

得到员工的上级然后再次得到员工的上级的上级等等

如何解决得到员工的上级然后再次得到员工的上级的上级等等

我有一个员工表,其中有一个列 Employee_ID 和 SuperiorID。我想获得特定员工的所有层级上级。比如Employee_ID-1000000的上级是1000001、1000002、1000003、1000004、1000005

+--------------------------+
| Employee_ID | SuperiorID |
+--------------------------+
|   1000000   |    1000001 |
|   1000001   |    1000002 |
|   1000002   |    1000003 |
|   1000003   |    1000004 |
|   1000004   |    1000005 |
+--------------------------+

Employee_ID - 1000005 是公司总裁。

我现在有一个问题:

DECLARE @EmployeeNo AS INT = 1000000
SELECT Superior_ID from EmployeeTable WHERE Employee_ID  = @EmployeeNo
UNION
SELECT Superior_ID from EmployeeTable WHERE Employee_ID  = (select Superior_ID from EmployeeTable WHERE Employee_ID  = @EmployeeNo)
UNION
SELECT Superior_ID from EmpoyeeTable WHERE Employee_ID = ( SELECT Superior_ID from EmployeeTable WHERE Employee_ID  = (select Superior_ID from EmployeeTable WHERE Employee_ID  = @EmployeeNo))
 

有没有更好的方法来做这个?

感谢您的帮助。

解决方法

是的,你需要 const containsVowels = string => { var lowerCase = string.toLowerCase(); var word = lowerCase.split(""); var vowelsArray = ["a","o","i","u","y"]; const result = word.filter(letter => vowelsArray.includes(letter)); return result.includes("a","y"); :

recursive cte
,

我们可以在这里使用递归分层查询。下面的策略是建立完整的层次结构,从员工 1000000 开始向上指挥链。递归在员工 1000004 处停止,其上级没有进一步的记录。在下面的递归 CTE 中,我跟踪一个计数器,它随着在层次结构上的每一步而增加。然后,我们使用 TOP 技巧仅选择排名最高的记录。

WITH cte (EmployeeID,SuperiorID,n) AS (
    SELECT Employee_ID,1
    FROM EmployeeTable
    WHERE Employee_ID = 1000000
    UNION ALL
    SELECT e.Employee_ID,e.SuperiorID,n+1
    FROM cte t
    INNER JOIN EmployeeTable e
        ON t.SuperiorID = e.Employee_ID
)

SELECT TOP 1 *
FROM cte
ORDER BY n DESC;

Demo

,

试试这个:

DECLARE     @EmployeeTable  TABLE   (EmployeeID int,SuperiorID int);
INSERT INTO @EmployeeTable
    VALUES  
            (1000000,1000001),(1000001,1000002),(1000002,1000003),(1000003,1000004),(1000004,1000005)
;

DECLARE @EmployeeNo int =   1000004,@President  int =   1000005
;

WITH    Employee    AS
    (
        SELECT 
                EmployeeID  =   @EmployeeNo
        UNION ALL
        SELECT  EmployeeID =  S.SuperiorID
        FROM    Employee        E
        JOIN    @EmployeeTable  S ON S.EmployeeID = E.EmployeeID
    )

SELECT * FROM Employee

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。