我有以下表员工(emp_id,name,salary,manager_id) 我想编写查询以检索manager_id和由该经理管理的所有员工工资的总和,或者甚至由该经理管理的经理管理。 我写了这样的查询:
Select manager_id , sum(salary)
from employees
connect by prior emp_id = manager_id
start manager_id = 100
group by manager_id;
但是我没有按照自己的意愿检索薪金。
答案 0 :(得分:1)
构建层次结构首先记住ROOT,然后按root分组。例如。 emp_id = 100的经理的薪水以及他/她经理的所有员工:
SELECT manager_id, SUM(salary) "Total_Salary"
FROM (
SELECT CONNECT_BY_ROOT emp_id as manager_id, Salary
FROM emploees
START WITH emp_id=100
CONNECT BY PRIOR emp_id = manager_id )
GROUP BY manager_id
ORDER BY manager_id;
答案 1 :(得分:1)
@ Serg的解决方案很好,但对于一位经理来说,即使是更简单的查询也可以:
select 21 as id, sum(salary) as summed
from employees e
start with emp_id = 21
connect by prior emp_id = manager_id;
如果您不想要经理的薪水,请添加where level<>1
。
测试数据:
create table employees(emp_id number(4), name varchar2(10),
salary number(6), manager_id number(4));
insert into employees values ( 1, 'King', 10000, null);
insert into employees values ( 11, 'Smith', 8000, 1);
insert into employees values ( 21, 'Jones', 9000, 1);
insert into employees values ( 211, 'Brown', 7500, 21);
insert into employees values ( 212, 'Adams', 6200, 21);
insert into employees values (2111, 'White', 5000, 211);
输出:
ID SUMMED
------ ----------
21 27700