Oracle tree計算葉子節點到根節點的乘積

來源:互聯網
上載者:User

  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  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.