[英]SQL Server - Self Join
I have a table as follows 我有一张桌子,如下
EmployeeID Name ManagerID
2 David 3
3 Roger NULL
4 Marry 2
5 Joseph 2
7 Ben 2
Here Roger is Top Manager Mike & David are Managers And rest all are employees 罗杰(Roger)是最高经理,迈克(Mike)&大卫(David)是经理,其余的都是员工
I am looking for output like this: 我正在寻找这样的输出:
EmployeeName ManagerName TopManager
Marry David Roger
Joseph David Roger
Ben David Roger
NULL David Roger
I tried using Self Join like: 我尝试使用自我加入,例如:
SELECT e1.Name EmployeeName, ISNULL(e2.name, 'Top Manager') AS ManagerName
FROM Employee e1
LEFT JOIN Employee e2
ON e1.ManagerID = e2.EmployeeID
but it is not giving the output I am looking for. 但它没有提供我想要的输出。
If you can have different top managers, then a recursive CTE is needed: 如果您可以拥有不同的高级管理人员,则需要递归CTE:
with cte as (
select employeeid, name, name as topmanager
from Employee
where managerid is null
union all
select t.employeeid, t.name, cte.topmanager
from Employee t join
cte
on t.managerid = cte.employeeid
)
select *
from cte;
If there is only one top manager, then: 如果只有一位高级经理,则:
select e.*, topm.name as topmanager
from employee e cross join
(select e2.* from employee e2 where e2.managerid is null) as topm
I think you have to do self join twice to get the desired output. 我认为您必须做两次自我连接才能获得所需的输出。
I created the query in this way and got the output which you have mentioned. 我以这种方式创建了查询,并获得了您提到的输出。 Please note that I did not include the last row which has null value, and rest the same as it is.
请注意,我没有包括具有空值的最后一行,其余部分保持不变。
Query: 查询:
create table Employees (EmployeeID int, Name varchar(10), ManagerID int)
Insert into Employees values
(2, 'David' , 3 )
,(3, 'Roger' , NULL)
,(4, 'Marry' , 2 )
,(5, 'Joseph' , 2 )
,(7, 'Ben' , 2 )
select e.name as EmployeeName, e1.name ManagerName, e2.Name TopManager
from Employees e
left join Employees e1 on e.ManagerID = e1.employeeid
left join Employees e2 on e1.ManagerID = e2.EmployeeID
where e.ManagerID is not null and e1.ManagerID is not null
Where condition was given to restrict the manager names in Employee column. 给出条件以限制“雇员”列中的经理姓名。
Output: 输出:
EmployeeName ManagerName TopManager
Marry David Roger
Joseph David Roger
Ben David Roger
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.