关于SQL查询?

时间:2012-03-30 12:33:04

标签: sql sql-server sql-server-2008 sql-server-2005

  

可能重复:
  Employee Manager Report - Sql Server

我有一个Employee表,如下所示:

Eno Ename   Mangerid
1    X      Null
2    Y      1
3    Z      2

但我希望结果如下所示

Ename    Managername
X        Null
Y        X
Z        y

任何人都可以给我答案吗?

提前致谢

5 个答案:

答案 0 :(得分:2)

这应该有效:

select 
    e.Ename,
    m.Ename as ManagerName
from employee e
left join employee m on e.ManagerId = m.Eno

答案 1 :(得分:0)

select e1.Ename employee, e2.Ename manager
from employee e1
join employee e2 on e1.ManagerId = e2.Eno

答案 2 :(得分:0)

在员工表上使用自我加入

    SELECT EMPLOYEE.ENAME as EmployeeName, EMPLOYEE.ENO as ManagerName
 FROM EMPLOYEE 
INNER JOIN EMPLOYEE AS EMPLOYEE_1 
ON EMPLOYEE.ENO = EMPLOYEE_1.MANEGERID

答案 3 :(得分:0)

您应该使用递归CTE

Recursive Queries Using Common Table Expressions

您可以根据需要深入了解层次结构。

答案 4 :(得分:0)

Select e.Name, (select m.name from Employee M where M.Eno =e.Mangerid) as Manager
from Employee e