简体   繁体   中英

SQL Self-join on the same line

I am trying to create a report that has employees first & last name along with their managers first and last names. I am trying to do a self join.

  • On the ERD there is:
    • EMP_NUM which is the employees ID
    • EMP_LNAME - Employee Last Name
    • EMP_FNAME - Employee First Name
    • EMP_MANAGER which is the manager ID(the manager ID is the same as the employees ID if the employee is a manager.)

I cant seem to get it to compile successfully. I am still learning, so any help/hints would be great. I am using Oracle SQL Developer.

 SELECT  EMPLOYEE.EMP_NUM "Employee ID",
 EMPLOYEE.EMP_LNAME "Employee First Name",
 EMPLOYEE.EMP_FNAME "Employee Last Name",
 EMPLOYEE.EMP_MANAGER "Managers ID for Employee",
 E2.EMP_LNAME as ManagerEMP_LNAME,
 E2.EMP_FNAME as ManagerEMP_FNAME
 FROM CARRM.EMPLOYEE
 left outer join CARRM E2 on EMPLOYEE.EMP_MANAGER = E2.EMP_NUM; 

In the from, you have mentioned the name of the table "Carrm.Employee" but in the left outer join, looks like you have only mentioned the name of your database "Carrm". Try the following

SELECT  E1.EMP_NUM "Employee ID",
E1.EMP_LNAME "Employee First Name",
 E1.EMP_FNAME "Employee Last Name",
 E1.EMP_MANAGER "Managers ID for Employee",
 E2.EMP_LNAME as ManagerEMP_LNAME,
 E2.EMP_FNAME as ManagerEMP_FNAME
 FROM CARRM.EMPLOYEE E1
 left outer join CARRM.Employee E2 on E1.EMP_MANAGER = E2.EMP_NUM; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM