2011-12-14 46 views
1

我有一張員工表,顯示員工編號,姓名和經理的員工編號。我試圖創建一個顯示emp名稱,emp#,經理姓名和mgr#的查詢。如何在SQL查詢中顯示僱員表中的經理姓名?

表看起來是這樣的:

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個colums

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

任何幫助,將不勝感激

回答

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 
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 
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(+) 
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; 
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 
+0

通常的計算工作,我們只是想要的數據 - 未裝飾。用戶界面和裝飾應該留給一個單獨的層面 - 而且您不應該處理或修飾空洞!在做所有這些事情時,你的答案也錯過了所有其他(有用的)列。 – 2013-07-10 09:41:07

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 
0

我想它工作得很好。

​​
1

嘗試此查詢

SELECT E2.EMPID,E2.EMPNAME,E1.EMPNAME 
AS MGRNAME 
FROM employee E1 
    INNER JOIN employee E2 ON E1.Empid=E2.ManagerId 
-1
Select e.ename empname , m.ename managername,e.empno empno ,m.mgr managerno from emp e, mgr m 
where m.empno=e.mgr 
相關問題