简体   繁体   中英

In SQL if a table have have colums empid,emp,salary,managerid…Then how we will find a result with colums as employee name, manager name, salary

If you are given table given in below structure.

empid | empname | salary | managerid

How will you find results as

empid | empname | salary | managername

because manager is also a part of employee

SELECT
 x.empid,
 x.empname as 'EmployeeName',
 x.salary as 'Salary',
 (SELECT empname FROM Tablename WHERE empid = x.managerid) as 'ManagerName'
FROM
 Tablename x

You can do a self-join, linking the ManagerId of the first table (employees) to the EmpId of the second use of Employee (managers):

SELECT e.empid, e.empname, e.salary
   , COALESCE(m.empname, 'NoManager') AS ManagerName
FROM Employee AS e
LEFT JOIN Employee AS m ON e.ManagerId = m.empId

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