2017-11-06 8 views
1

테이블 및 삽입 값을 만들려면 다음 SQL 문을 사용하여 :SQL 재귀 쿼리 및 출력

create table tb(id int , pid int , name nvarchar(10)) 
insert into tb values(1 , null , 'A') 
insert into tb values(2 , null , 'B') 
insert into tb values(3 , null , 'C') 
insert into tb values(4 , 1 , 'D') 
insert into tb values(5 , 1 , 'E') 
insert into tb values(6 , 2 , 'F') 
insert into tb values(7 , 3 , 'G') 
insert into tb values(8 , 4 , 'H') 
insert into tb values(9 , 5 , 'I') 

을 그리고 루트에서이 같은 잎이 나무의 각 행을 표시하려면에게 최종 출력을 원하는 :

A-D-H 
A-E-I 
B-F 
C-G 

누구든지이 작업을 수행하는 SQL 프로 시저를 작성하는 방법을 알고 있습니까? 감사.

+0

어떤 DBMS를 사용하고 있습니까? – jarlh

+0

https://stackoverflow.com/questions/tagged/recursive-query+hierarchical-data+sql –

답변

2

SQL Server를 사용하는 경우 재귀 쿼리를 사용하여 해결할 수 있습니다. 유사한 접근법이 Oracle과 PostgreSQL에서 사용될 수 있습니다.

with rcte as 
(
    select t1.id, t1.pid, cast(t1.name as nvarchar(100)) name 
    from tb t1 
    where not exists (select 1 from tb t2 where t2.pid = t1.id) 
    union all 
    select tb.id, tb.pid, cast(concat(tb.name, '-', rcte.name) as nvarchar(100)) name 
    from rcte 
    join tb on rcte.pid = tb.id 
) 
select name 
from rcte 
where rcte.pid is null 

demo

그것은 먼저 리프 노드를 발견 한 후 루트까지 통과

.