每个经理直接或间接工作的员工的打印数量(oracle)

时间:2014-02-07 04:32:44

标签: sql oracle11g

我有一个像

这样的员工表
managername varchar2(20),
salary number(10,2),
empname varchar2(20),
Constraint [PK_Emp] Primary key (empname),
Constraint [FK_Emp] Foreign key (managername) references employee (empname) on delete cascade

mangername         salary        empname
------         ------         --------------
""              1000              Sumanta
Sumanta         1000              Arpita
Sumanta         1000              Pradip
Arpita          1000              Sujon
Sujon           1000              Arpan
Sujon           1000              Jayanti

我想了解直接或间接在每位经理下工作的所有员工

1 个答案:

答案 0 :(得分:0)

您可以使用递归CTE执行此操作:

with cte(managername, empname, level) as (
      select managername, empname, 0
      from employee
      union all
      select e.managername, cte.empname, level + 1
      from cte join
           employee e
           on cte.managername = e.empname
    )
select managername, count(*)
from cte
group by managername;

这应该适用于11g第2版。SQL Fiddle似乎有问题,尽管基本相同的代码适用于SQL Server