1

问题描述:

我需要从给定表中为特定 ID 找到 Ultimate Manager 的名称(或 ID)。
也就是说,例如让:

3 has manager ID 4
4 has manager id 5,
5 has manager ID 109

所以如果我给 cemp_id 3 我应该得到经理 ID 109。

我尝试了以下查询:

SELECT C.CUSTOMERID       AS ChildId, 
       P.CUSTOMERID       AS ParentId, 
       P.PARENTCUSTOMERID AS GrantParentId, 
       C.CUSTOMERNAME 
FROM   CUSTOMER_PROFILE C 
       JOIN CUSTOMER_PROFILE P 
         ON C.PARENTCUSTOMERID = P.CUSTOMERID 

但这仅适用于 2 个层次结构,我需要它用于 N 个层次结构。

4

1 回答 1

2

如果您使用 SQL Server 2008 或更高版本:

declare @id int = 1

;with cte
as
(
    select PARENTCUSTOMERID, 0 as level 
    from CUSTOMER_PROFILE where CUSTOMERID = @id

    union all

    select t.PARENTCUSTOMERID, cte.level  + 1 as level
    from CUSTOMER_PROFILE t
    inner join cte on t.CUSTOMERID = cte.PARENTCUSTOMERID 

)

select top 1 PARENTCUSTOMERID from cte
order by level desc
于 2013-10-07T11:39:14.070 回答