1 回答

TA貢獻1858條經驗 獲得超8個贊
Oracle tree計算葉子節點到根節點的乘積
1.//有下面一棵二叉樹,轉換為表結構:
2.parent_id child_id weight
3.------ ------- ------
4.a b 2
5.b c 3
6.c d 4
7.b e 7
8.c f 2
9.//計算葉子節點到根節點之間邊的權值的乘積: 10.leaf weight
11.---- ------
12.d 24
13.e 14
14.f 12
15.//數據 16.create table tree (parent_id varchar2(10),child_id varchar2(10),weight number(2));
17.insert into tree values('a','b',2); 18.insert into tree values('b','c',3); 19.insert into tree values('c','d',4); 20.insert into tree values('b','e',7); 21.insert into tree values('c','f',2); 22.//創建一個函數實現求字串乘積(動態SQL) 23.create or replace function func_tree(str in varchar2) 24.return number 25.as 26. num number;
27.begin
28. execute immediate 'select '||str||' from dual' into num; 29. return num; 30.end func_tree;
31.//sql代碼: 32.select child_id, func_tree(substr(sys_connect_by_path(weight, '*'), 2)) weight 33.from tree t
34.where connect_by_isleaf = 1
35.start with not exists (select 1 from tree where t.parent_id=child_id)
36.connect by prior child_id = parent_id
37.order by child_id;
38.//結果: 39.CHILD_ID WEIGHT
40.---------- ----------
41.d 24
42.e 14
43.f 12
- 1 回答
- 0 關注
- 239 瀏覽
添加回答
舉報