如何在SQL查询中显示employee表中的管理器名称?

时间:2011-12-14 18:56:16

标签: sql oracle

我有一张员工表,显示员工编号,姓名和经理的员工编号。我正在尝试创建一个显示emp名称,emp#,manager name和mgr#的查询。

表格如下:

EMPNO ENAME  JOB       MGR  HIREDATE  SAL COMM DEPTNO 
7839  KING   PRESIDENT -    17-NOV-81 5000 -   10 
7698  BLAKE  MANAGER   7839 01-MAY-81 2850 -   30 
7782  CLARK  MANAGER   7839 09-JUN-81 2450 -   10 
7566  JONES  MANAGER   7839 02-APR-81 2975 -   20 
7654  MARTIN SALESMAN  7698 28-SEP-81 1250 1400 30 
7499  ALLEN  SALESMAN  7698 20-FEB-81 1600 300 30 
7844  TURNER SALESMAN  7698 08-SEP-81 1500 0   30 
7900  JAMES  CLERK     7698 03-DEC-81 950  -   30 
7521  WARD   SALESMAN  7698 22-FEB-81 1250 500 30 
7902  FORD   ANALYST   7566 03-DEC-81 3000 -   20 

其中三列非常简单,因为它们在表格中,但是如果我拥有的是经理的员工编号,我将如何添加经理名称?

这是我到目前为止只显示3个列的

select ename as "Employee", empno as "Emp#", mgr as "Mgr#"  from emp;

任何帮助将不胜感激

9 个答案:

答案 0 :(得分:9)

select 
  emp.ename as "Employee", 
  emp.empno as "Emp#", 
  emp.mgr as "Mgr#",
  m.ename as "Manager"
from 
 emp
  LEFT OUTER JOIN emp m ON
   emp.mgr = m.empno

答案 1 :(得分:4)

试试这个:

select e.ename ,e.sal, (select s.grade from salgrade s where e.sal between s.losal and s.hisal) empgrade ,e2.ename"mgr", e2.sal mgrsal,
(select s.grade from salgrade s where e2.sal between s.losal and s.hisal) mgrgrade from emp e,emp e2
where e.mgr=e2.empno(+)

答案 2 :(得分:2)

select
  e.ename as "Employee",
  e.empno as "Emp#",
  e.mgr as "Mgr#",
  m.ename as "MgrName"
from emp e
join emp m on e.mgr = m.empno

答案 3 :(得分:1)

SELECT DISTINCT E.ENAME,E.job 
   FROM EMP E 
   JOIN EMP Y 
     ON E.EMPNO=Y.MGR; 

这将为您提供作为经理的独特员工姓名。

或者:

SELECT E.ENAME,E.job 
   FROM EMP E 
   JOIN EMP Y 
      ON E.EMPNO=Y.MGR;

或者:

SELECT E.ENAME,E.job 
   FROM EMP E, EMP Y 
   WHERE 
     E.EMPNO=Y.MGR;

答案 4 :(得分:1)

select   e.ename as "Employee",  e.empno as "Emp#",  e.mgr as "Mgr#",  m.ename as "MgrName" from emp e ,  emp m   on e.mgr = m.empno

答案 5 :(得分:1)

尝试此查询

SELECT E2.EMPID,E2.EMPNAME,E1.EMPNAME 
AS MGRNAME 
FROM employee E1 
   INNER JOIN employee E2 ON E1.Empid=E2.ManagerId

答案 6 :(得分:0)

SELECT (CASE 
WHEN e1.manager_id IS NULL THEN
  e1.last_name ||' IS THE PRESIDENT'
ELSE
  e2.last_name || ' IS THE MANAGER OF '||e1.last_name
END)"HIERARCHY" FROM hr.employees e1, hr.employees e2 WHERE e1.manager_id = e2.employee_id(+) ORDER BY e1.manager_id NULLS FIRST

答案 7 :(得分:0)

我试过它工作正常。

SELECT a.empno EmpID,a.empname EmpName, a.mgrid MgrID,(select empname from employee where empno = a.mgrid) MgrName 
from employee a, employee b
where a.empno = b.empno order by a.empno asc;

答案 8 :(得分:-1)

Select e.ename empname , m.ename managername,e.empno empno ,m.mgr managerno from emp e, mgr m
where m.empno=e.mgr