2017-11-06 4 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

これは、最初のリーフ・ノードを発見し、それはルートまで横断。