从表EMP和DEPT我想得到所有部门经理的员工,按deptno分组: (例如10 KING,CLARK,20 KING,JONES,SCOTT,FORD ......,30 BLAKE,KING ..) 在这个表中存在"经理"这意味着"经理",例如:CLARK在10号部门工作,他的mgr是7839,这是KING的empno。这意味着" KING是10"部门的管理人员之一。 。我的问题是如何编写一个查询,返回所有在部门10,20,30中工作的管理者的结果?如何加入mgr和empno?
DEPTNO DNAME EMPNO ENAME
10 ACCOUNTING 7782 CLARK
10 ACCOUNTING 7839 KING
10 ACCOUNTING 7934 MILLER
20 RESEARCH 7566 JONES
20 RESEARCH 7902 FORD
20 RESEARCH 7876 ADAMS
20 RESEARCH 7369 SMITH
20 RESEARCH 7788 SCOTT
30 SALES 7521 WARD
30 SALES 7844 TURNER
30 SALES 7499 ALLEN
30 SALES 7900 JAMES
30 SALES 7698 BLAKE
30 SALES 7654 MARTIN
insert into emp values (7369, 'SMITH', 'CLERK', 7902, to_date('17-DEC-80'), 800, NULL, 20);
insert into emp values (7499, 'ALLEN', 'SALESMAN', 7698, to_date('20-FEB-81'), 1600, 300, 30);
insert into emp values (7521, 'WARD', 'SALESMAN', 7698, to_date('22-FEB-81'), 1250, 500, 30);
insert into emp values (7566, 'JONES', 'MANAGER', 7839, to_date('02-APR-81'), 2975, NULL, 20);
insert into emp values (7654, 'MARTIN','SALESMAN', 7698, to_date('28-SEP-81'), 1250, 1400, 30);
insert into emp values (7698, 'BLAKE', 'MANAGER', 7839, to_date('01-MAY-81'), 2850, NULL, 30);
insert into emp values (7782, 'CLARK', 'MANAGER', 7839, to_date('09-JUN-81'), 2450, NULL, 10);
insert into emp values (7788, 'SCOTT', 'ANALYST', 7566, to_date('19-APR-87'), 3000, NULL, 20);
insert into emp values (7839, 'KING', 'PRESIDENT', NULL, to_date('17-NOV-81'), 5000, NULL, 10);
insert into emp values (7844, 'TURNER','SALESMAN', 7698, to_date('08-SEP-81'), 1500, 0, 30);
insert into emp values (7876, 'ADAMS', 'CLERK', 7788, to_date('23-MAY-87'), 1100, NULL, 20);
insert into emp values (7900, 'JAMES', 'CLERK', 7698, to_date('03-DEC-81'), 950, NULL, 30);
insert into emp values (7902, 'FORD', 'ANALYST', 7566, to_date('03-DEC-81'), 3000, NULL, 20);
insert into emp values (7934, 'MILLER','CLERK', 7782, to_date('23-JAN-82'), 1300, NULL, 10);
INSERT INTO DEPT VALUES (10, 'ACCOUNTING', 'NEW YORK');
INSERT INTO DEPT VALUES (20, 'RESEARCH', 'DALLAS');
INSERT INTO DEPT VALUES (30, 'SALES', 'CHICAGO');
INSERT INTO DEPT VALUES (40, 'OPERATIONS', 'BOSTON');
预期结果必须是(d.deptno,d.dname,e.empno,e.ename):deptno 10(KING,CLARK),deptno 20(KING,JONES,SCOTT,FORD)和deptno 30( BLAKE,KING)。
答案 0 :(得分:1)
如果我理解正确,并且将来尝试用表结构,输入和预期输出更好地解释,那么这就是你需要的:
SELECT d.depNO,d.DNAME,e.EMPNO,e.ENAME
FROM EMP e
INNER JOIN dept d
ON(e.depno = d.depno)
WHERE EXISTS(select 1 from EMP t where t.mgr = e.empNO)
AND d.depNO in(10,20,30)
这会将表连接在一起,仅过滤部门10 20和30,并检查该员工是否存在他是其经理的另一名员工。
编辑:如果你想要的是深入挖掘,如果所有部门的人都是管理员,那么他应该出现在每个部门上,那么这就是你所需要的:
SELECT distinct d.depNO,d.DNAME,e2.EMPNO,e2.ENAME
FROM EMP e
INNER JOIN dept d
ON(e.depno = d.depno)
INNER JOIN EMP e2
ON e2.EMPNO = e.mgr
where d.depNO in(10,20,30)