寻找终极经理ID

时间:2013-10-07 11:07:15

标签: sql sql-server

问题描述:

我需要从Given表中找到特定ID的终极经理姓名(或ID) 也就是说,对于eg eg:

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级层次结构。

1 个答案:

答案 0 :(得分: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