2013-02-24 2 views
2

SQL Server CTE 예제를 찾고 각 계층을 병합하는 것과 같은 모든 계열을 출력 할 수있는 방식으로 계층 구조를 만들 수 있습니다. 나는 + 부모의 행 세부 SQL Server CTE를 사용하여 계층 구조 계층 병합

형상 부재의 세부 사항을 각 가정의 일원이의 계층 구조 목록의 목록이 필요 조부모 에서 루트 시작하면 가족 트리의 예는
child1 row 
    child1 +Parent row 
    child1 + Grand parent Row 

    child2 Row 
    child2 + parent row 
    child2 + grand parent's row 

and so on 
 CREATE TABLE Family(id int NULL, 
Name varchar(20) null, Parent_id int NULL, level int NULL ) 


INSERT INTO Family VALUES 
    (1, 'Grand Parent',NULL, 1),   
    (2, 'Parent' , 1,  2), 
    (3, 'Child1' , 2,  3), 
    (4, 'Child2' , 2,  3)  

    select * from Family; 

id Name   Parent_id level 
1 Grand Parent NULL   1 
2 Parent  1   2 
3 Child1  2   3 
4 Child2  2   3 

이것은 내가에서 할 수있는 것입니다 이 점. 상위 행의 세부 사항은 5 및 6 열에 있습니다.

with cte as 
(
    select ID,Parent_id,level,Name,id as parent_id,level, 'a' as type 
     from family 
     --where ID=3 
    union all 
    select f.ID,f.Parent_id,f.level,f.Name,c.id as parent_id,c.level, 'r' as type 
    from family f 
    inner join cte c 
    on f.parent_id=c.id 
) 
select * from cte order by id 

결과는 다음과 같습니다. (5 및 6 열 참고)

Child_ID Parent_id Child_level Name parent_id level 
1   NULL  1   Grand Parent 1   1 
2   1   2   Parent   2   2 
2   1   2   Parent   1   1 
3   2   3   Child1   1   1 
3   2   3   Child1   2   2 
3   2   3   Child1   3   3 
4   2   3   Child2   4   3 
4   2   3   Child2   2   2 
4   2   3   Child2   1   1 

미리 감사드립니다.

답변

9
with cte as (
    select ID, Name, level, Parent_id 
    from family 

    union all 

    select cte.ID, cte.Name, cte.level, family.Parent_id 
    from cte 
    inner join family on cte.Parent_id = family.ID 
) 
select cte.ID as Child_ID, f2.Parent_ID, cte.level as Child_level, cte.Name, isnull(cte.Parent_id, cte.ID) as parent_ID, isnull(f.level, cte.level) as level 
from cte 
left outer join family f on cte.Parent_id = f.ID 
inner join family f2 on cte.id = f2.ID 
order by 1, 5 
+0

결과에서 상위 및 상위 부모 행만 숨 깁니다. 원래 게시물에 표시된 것과 같은 수의 행이 필요하지만 5,6 개의 결과는 예상 한 것과 다릅니다. – Jem

+0

좋아, 지금 무슨 뜻인지 알 겠어. 나는 이것이 당신이 겪은 일이라고 생각합니다. – muhmud

+0

거의 없습니다. 그냥 마지막 열이 필요합니다. 나는 질문을 업데이트했다. 마지막 표에서 예상 결과를 확인하십시오. – Jem