Oracle資料庫入門教程 層次樹統計

來源:互聯網
上載者:User

統計部門的員工個數(員工個數=本部門人數+下級部門人數)

部門表:


員工表:




sql 語句:

  1. with temp as(      
  2.   select t1.deptid as id, t1.supdeptid parent, num, level levs,t1.deptname      
  3.     from dept t1      
  4.     left join (select deptid, count(t.deptid) num      
  5.                  from emp t      
  6.                 group by t.deptid) t2 on t1.deptid = t2.deptid      
  7.    start with t1.supdeptid is null  
  8.   connect by prior t1.deptid = t1.supdeptid)      
  9.     select lpad(' ', 4 * levs, ' ')||id as id,lpad(' ', 4 * levs, ' ')||deptname as deptname,      
  10.            (select nvl(num, 0) from temp where id = t.id) +      
  11.            (select nvl(sum(num), 0)      
  12.               from temp     
  13.             connect by parent = prior id      
  14.              start with parent = t.id) cnt      
  15.       from temp t   

查詢結果:




Oracle10g sql語句:

  1. select a.root as id, nvl(sum(b.num), 0) num   
  2.   from (select id, fid, connect_by_root(id) root   
  3.           from (select d.deptid as id, d.supdepid as fid from dept d start with d.supdepid is null  
  4.   connect by prior d.deptid = d.supdepid)   
  5.         connect by prior id = fid) a   
  6.   left join (select deptid, count(t.deptid) num from emp t group by t.deptid) b on a.id =   
  7.                                                                                    b.deptid   
  8.  group by root   
  9.  order by root;  

相關文章

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.