2014-11-19 2 views
0

내일 생산 서버 (SQL 서버)에서 보고서를 실행해야합니다. CTE에 대한 자신감이 부족하고 빠른 도움이 필요하므로 여기에 검색어를 올리겠습니다.CTE를 사용하여 궁극적 인 부모 찾기

는이 같은 테이블 구조 뭔가를 :

테이블 :

UnderLyingConstituentMap 
{ 
ParentUnderLyingId int not null, 
UnderLyingId int 
} 

하나 UnderLying 하나 이상의 ParentUnderLying의 일부가 될 수 있습니다. 그래서 많은 관계가 있습니다. UnderLyingId 세트를 받았으며 모든 궁극적 인 ParentUnderLyingId을 찾을 필요가 있습니다.

부모가없는 UnderLying이있을 수 있습니다. 그렇다면 그들은이 표의 UnderLyingId 란에 존재하지 않을 것입니다.

CTE 쿼리를 도와주세요.

답변

0

사용 재귀는 다음과 같이 조인

WITH UserCTE AS (
    SELECT UnderLyingId ,ParentUnderLyingId 
    FROM dbo.UnderLyingConstituentMap 
    WHERE UnderLyingId = 1 

    UNION ALL 

    SELECT UnderLyingId ,ParentUnderLyingId 
    FROM UserCTE AS usr 
    INNER JOIN dbo.UnderLyingConstituentMap AS mgr 
     ON usr.ParentUnderLyingId = mgr.UnderLyingId 
) 
SELECT * FROM UserCTE AS u; 
0

은 아래의 쿼리

;WITH cte1 
as 
(
    SELECT ParentUnderLyingId,UnderLyingId, 0 AS level , 
    convert(varchar(100), '<'+convert(varchar(3),UnderLyingId)+'>') as Visited 
    FROM #UnderLyingConstituentMap 

    UNION ALL 

    SELECT T.ParentUnderLyingId,T.UnderLyingId, level +1 , 
    Convert(varchar(100),Visited +'<'+convert(varchar(3),cte1.ParentUnderLyingId)+'>') 
    FROM #UnderLyingConstituentMap T 
    INNER JOIN cte1 
    on t.UnderLyingId=cte1.ParentUnderLyingId 
    WHERE Visited NOT LIKE ('%<'+convert(varchar(3),t.ParentUnderLyingId)+'>%') 
) 
SELECT * FROM cte1 
으로 시도
관련 문제