假设我有一个如下表:
ID Name ManagerID
1 Dave NULL
2 Scott 1
3 Mike 1
4 Nick 3
5 Jack 1
如何查找所有员工的相应经理姓名,如下面的格式?
ID Name ManagerID ManagerName
1 Dave NULL NULL
2 Scott 1 Dave
3 Mike 1 Dave
4 Nick 3 Mike
5 Jack 1 Dave
答案 0 :(得分:1)
试试这个!
select a.ID,a.Name,a.ManagerID,b.Name as ManagerName
from #t a left join #t b on a.ManagerID=b.ID
答案 1 :(得分:0)
select ID, Name, ManagerID,
(case when managerid is null then null else (select Name from tab where id=managerid) end) as ManagerName
from tab
你也可以这样做
答案 2 :(得分:0)
可能有多种方式。 如:
SELECT
ID, Name, ManagerID,
(SELECT Name FROM table AS ManagersTable WHERE ManagersTable.ID=EmployeesTable.ManagerID) AS ManagerName
FROM table AS EmployeesTable