Oracle数据库入门教程 层次树统计


统计部门的员工个数(员工个数=本部门人数+下级部门人数)

部门表:


员工表:




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;  

相关内容