Search This Blog

EmployeeName with their ManagerName in SQL

EmployeeName with their ManagerName in SQL  


A common Interview question asked by interviewer to display all EmployeeName with their Manager Name.
Its not only a interview question but also in many situation you have to fetch the ManagerNames with their Employees.

So below is the solution with sample table

Consider below table

create table employeemanager1
(empid int identity(1,1),
employeename nvarchar(100),
ManagerId nvarchar(100)


insert into employeemanager values('E1',3),('E2',1),('E3',1),('E4',2)

select * from employeemanager

empid employeename ManagerId
1 E1 3
2 E2 1
3 E3 1
4 E4 2

If you will see the table, the table is displaying EmpiD with their Name and their ManagersID . A Manager is Also an Employee
So we have to display EmpID,EMployeeName and their ManagerName
Eg E1 has Manager E3 ......

--Self join Showing employeeName with their Manager Names
select e.empid , e.employeename,em.employeename as ManagerName from employeemanager e join 
employeemanager em on em.empid  =e.ManagerId  

empid employeename ManagerName
1 E1 E3
2 E2 E1
3 E3 E1
4 E4 E2

Now sql is showing all Employee with their ManagersName.

No comments:

Post a Comment