Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sql server - SQL query to get the employee name and their manager name from the same table

Employee table

Employee_id  Employee_name   Manager_id
-------------------------------------
Emp00001     Ram             Emp00005
Emp00002     Sharath         Emp00003
Emp00003     Nivas           Emp00005
Emp00004     Praveen         Emp00002
Emp00005     Maharaj         Emp00002

Output

Employee Name    Manager Name
------------------------------
Ram              Maharaj
Sharath          Nivas
Nivas            Maharaj
Praveen          Sharath
Maharaj          Sharath

In the employee table, there are three columns Employee_id, employee_name and manager_id. From the table, how to fetch the employee name and their manager name?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can self-join the table to get the manager's name from his ID:

SELECT e.employee_name, m.employee_name AS manager_name
FROM   employee e
JOIN   employee m on e.manager_id = m.employee_id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...