Self Join to get employee manager name Self Join to get employee manager name sql sql

Self Join to get employee manager name


CREATE VIEW ASSELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,        e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerNameFROM   tblEmployeeDetails e1       JOIN tblEmployeeDetails e2       ON e1.emp_mgr_id = e2.emp_id

EDIT:Left Join will work if emp_mgr_id is null.

CREATE VIEW AS SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,         e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName FROM   tblEmployeeDetails e1        LEFT JOIN tblEmployeeDetails e2        ON e1.emp_mgr_id = e2.emp_id


   SELECT b.Emp_id, b.Emp_name,e.emp_id as managerID, e.emp_name as managerName    FROM Employee b    JOIN Employee e ON b.Emp_ID = e.emp_mgr_id

Try this, it's a JOIN on itself to get the manager :)


CREATE VIEW EmployeeWithManager AS SELECT e.[emp id], e.[emp name], m.[emp id], m.[emp name] FROM Employee e LEFT JOIN Employee m ON e.[emp mgr id] = m.[emp id]

This definition uses a left outer join which means that even employees whose manager ID is NULL, or whose manager has been deleted (if your application allows that) will be listed, with their manager's attributes returned as NULL.

If you used an inner join instead, only people who have managers would be listed.