Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

i want to find all managers names and their all managers name in oracle SQL

select e.last_name, ee.last_name 
from employees e join employees ee on (e.manager_id = ee.employee_id) 
where last_name in (select last_name 
                    from employees 
                    where employee_id in (select distinct manager_id 
                                          from employees
                                         )
                   );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood you correctly, you want to select managers only.

The following example is based on Scott's schema.

Here are all employees, along with their managers (hierarchically) so that it is easier to spot the managers.

SQL> select lpad(' ', (level - 1) * 2) || ename ename
  2  from emp
  3  start with mgr is null
  4  connect by prior empno = mgr;

ENAME
------------------------------------------------------
KING              -- manager
  JONES           -- manager
    FORD          -- manager
      SMITH       -- employee
  BLAKE           -- manager
    ALLEN         -- employee
    WARD          -- employee
    MARTIN        -- employee
    TURNER        -- employee
    JAMES         -- employee
  CLARK           -- manager
    MILLER        -- employee

12 rows selected.

SQL>

Additional WHERE clause returns managers only:

SQL> select lpad(' ', (level - 1) * 2) || ename ename
  2  from emp
  3  where empno in (select mgr from emp)
  4  start with mgr is null
  5  connect by prior empno = mgr;

ENAME
--------------------------------------------------------
KING
  JONES
    FORD
  BLAKE
  CLARK

SQL>

Substituting what is getting selected with SYS_CONNECT_BY_PATH, we'll get a different output:

SQL> select sys_connect_by_path(ename, ' / ') path
  2  from emp
  3  where empno in (select mgr from emp)
  4  start with mgr is null
  5  connect by prior empno = mgr;

PATH
----------------------------------------------------
 / KING
 / KING / JONES
 / KING / JONES / FORD
 / KING / BLAKE
 / KING / CLARK

SQL>

Or, following your steps, with a self-join of the EMP table, we get

SQL> select m1.ename manager, m2.ename his_manager
  2  from emp m1 join emp m2 on m1.mgr = m2.empno
  3  where m1.empno in (select mgr from emp);

MANAGER    HIS_MANAGER
---------- -------------
FORD       JONES
CLARK      KING
BLAKE      KING
JONES      KING

SQL>

Pick the one that suits you best. I believe other members will suggest other options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...