首页 > 解决方案 > 递归 CTE 在 SQL Server 中查找层次结构中的第一个管理器

问题描述

我有一个用户表

在此处输入图像描述

我想通过他们的工作位置层次结构为每个用户找到他们的第一个经理。

我设法编写了这个脚本,但我似乎无法让它正常工作。我需要用户 1003 必须有 1001 managerId。现在它显示 1002。

在此处输入图像描述

select 1001 as userid, 'L1' as locationCode, NULL as parentLocationCode, 1 as isManager into #Users union all
select 1002 as userid, 'L2' as locationCode, 'L1' as parentPad, 0 as isManager union all
select 1003 as userid, 'L3' as locationCode, 'L2' as parentPad, 0 as isManager 

;WITH cte_org AS (
    SELECT       
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,null as managerId
    FROM       
        #Users as d
    WHERE d.parentLocationCode is NULL
    UNION ALL
    SELECT 
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,o.userid as managerId
    FROM 
        #Users as d
        inner JOIN cte_org o on d.parentLocationCode=o.locationCode
)
SELECT *
FROM cte_org
OPTION (MAXRECURSION 32767);

标签: sqlsql-serverrecursioncommon-table-expression

解决方案


您只需使用 userId 为 manager 设置 managerId,然后将 managerId 复制到链接记录

select 1001 as userid, 'L1' as locationCode, NULL as parentLocationCode, 1 as isManager into #Users union all
select 1002 as userid, 'L2' as locationCode, 'L1' as parentPad, 0 as isManager union all
select 1003 as userid, 'L3' as locationCode, 'L2' as parentPad, 0 as isManager 
;

WITH
cte_org AS (
    SELECT       
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,d.userid as managerId
    FROM       
        #Users as d
    WHERE d.parentLocationCode is NULL
    UNION ALL
    SELECT 
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,o.managerId as managerId
    FROM 
        #Users as d
        inner JOIN cte_org o on d.parentLocationCode=o.locationCode
)
SELECT *
FROM cte_org
OPTION (MAXRECURSION 32767);

userid  locationCode    parentLocationCode  isManager   managerId
1001    L1                                  1           1001
1002    L2              L1                  0           1001
1003    L3              L2                  0           1001

推荐阅读