我有下表
empid empname managerID
1 A NULL
2 B 1
3 C 1
4 D 2
ddl在
之下Declare @t table(empid int, empname varchar(20), managerID int)
insert into @t
select 1,'A',null union all
select 2,'B',1 union all
select 3,'C',1 union all
select 4,'D',2
我要做的是准备一份报告,说明哪些员工向哪位经理报告。
我已经使用
进行了宣传select EmpName = e.empname, ManagerName = m.empname
from @t e
left join
@t m
on e.managerID = m.empid
,所需的输出为
EmpName ManagerName
A NULL
B A
C A
D B
这样做的其他方法是什么?
答案 0 :(得分:1)
Declare @t table(empid int, empname varchar(20), managerID int) insert into @t select 1,'A',null union all select 2,'B',1 union all select 3,'C',1 union all select 4,'D',2 ;with CTE AS ( Select empid,empname,managerID, Cast(empname As Varchar(max)) As ReportingManager from @T where managerID is null UNION ALL Select T.empid,T.empname,T.managerID, Cast(CTE.empname+'->'+t.empname As Varchar(max)) As ReportingManager from @T As T INNER JOIN CTE ON T.managerID=CTE.empid ) SELECT * FROM CTE
答案 1 :(得分:0)
我认为,您的解决方案是最合适的,但我们可以重写它,例如:
select t1.empname [EmpName]
, (select t2.empname from @t t2 where t2.empid = t1.managerID) [ManagerName]
from @t t1
答案 2 :(得分:0)
自我加入表格
案例1:所有拥有经理的员工
select e1.empname employee, e2.empname manager
from employee e1
join employee e2 on e1.managerId = e2.empid
order by e2.name,e1.name
案例2:所有拥有经理的员工
select e1.empname employee, COALESCE(e2.empname,'none') manager
from employee e1
left join employee e2 on e1.managerId = e2.empid
order by e2.name,e1.name
答案 3 :(得分:0)
好的,所以你问其他方法。这有点怪异。
CREATE TABLE employee (empid int, empname varchar(20), managerID int)
GO
insert into employee
select 1,'A',null union all
select 2,'B',1 union all
select 3,'C',1 union all
select 4,'D',2
GO
CREATE FUNCTION [dbo].[GetEmployeeTree](@ManagerId int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN
(SELECT empID as '@Id',
empname AS '@Name',
dbo.GetEmployeeTree(empid)
FROM employee em
WHERE ManagerId=@ManagerId
FOR XML PATH('Employee'), TYPE)
END
GO
SELECT empID as '@Id',
empname AS '@Name',
dbo.GetEmployeeTree(empId)
FROM employee
WHERE managerId is null
FOR XML PATH('Employee'), ROOT('Employees')
提供此输出
<Employees>
<Employee Id="1" Name="A">
<Employee Id="2" Name="B">
<Employee Id="4" Name="D" />
</Employee>
<Employee Id="3" Name="C" />
</Employee>
</Employees>
我实际上已经使用它来生成具有数万个节点的大型XML树,而且速度非常快。可能有一种方法将根查询与子查询合并,我还没有完全弄明白。当我过去使用这种技术时,我使用了一个单独的链接和节点表来定义层次结构,当你这样做时它会更清晰。