oracle 层次树统计

来源:互联网 发布:开淘宝店一个月赚3万 编辑:程序博客网 时间:2024/05/07 09:52

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

部门表: 
 

员工表: 

 


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   

查询结果: