db2樹形結構sql問題(轉)

今天在論壇中看到一個很有意思的題目,拿來分享一下:
[color=red]創建table的語句:
CREATE TABLE TEST_TREE (

"ID" BIGINT NOT NULL ,

"FARTHERID" BIGINT NOT NULL ,

"NAME" VARCHAR(50) NOT NULL )
插入數據的語句:
insert into TEST_TREE values(1001,0,'中國'),(100101,1001,'山東'),(100102,1001,'河北'),(100103,1001,' 湖北'),(10010101,100101,'濟南'),(10010102,100101,'青島'),(10010201,100102,'石家莊 '),(10010202,100102,'楊柳青'),(10010301,100103,'武漢'),(10010103,100103,'荊州')

要求sql生成的數據結構爲:
中國 山東 濟南
中國 山東 青島
中國 河北 石家莊
中國 河北 楊柳青
中國 湖北 武漢
中國 湖北 荊州[/color]
該如何解決呢?
解決的辦法是使用了個臨時表,用遞歸的方式生成。語句如下:
select * from temp.TEST_TREE;

with t ( id,name,seq)
as (
select id,name,0 from temp.TEST_TREE
where fartherid=0
union all
select a.id,b.name||' '||a.name,seq +1 from temp.TEST_TREE a,t b
where a.fartherid=b.id
)
select name from t where seq=2;
答案顯示正確。

遞歸的過程通過如下的語句可以看出來:

with t ( id,name,seq)
as (
select id,name,0 from temp.TEST_TREE
where fartherid=0
union all
select a.id,b.name||' '||a.name,seq +1 from temp.TEST_TREE a,t b
where a.fartherid=b.id
)

select name as name0,0 from t where seq=0
union all
select name as name1 ,1 from t where seq=1
union all
select name as name2,2 from t where seq=2


結果中顯示爲:
'中國' 0
'中國 河北' 1
'中國 山東' 1
'中國 湖北' 1
'中國 河北 石家莊 ' 2
'中國 河北 楊柳青' 2
'中國 山東 濟南' 2
'中國 山東 青島' 2
'中國 湖北 武漢' 2
'中國 湖北 荊州' 2
發佈了46 篇原創文章 · 獲贊 0 · 訪問量 4314
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章