有两个表,一个包含分层员工数据,
Id,Name,ManagerId
1,Boss,NULL
2,经理A,1
3,经理B,1
4,LeadC,2
5,EngineerD,4
...
另一张表包含谁是每个部门的负责人
Id,Department
2,发展
3,销售
4,ProjectX
现在我想基于第一个表创建一个View,但是还有一个Department列,由最近的祖先确定,该祖先在表2中有条目。是否可以使用单个SQL语句?
Id,Name,ManagerId,Department
1,Boss,NULL,NULL
2,经理A,1,发展
3,经理B,1,销售
4,LeadC,2,ProjectX
5,EngineerD,4,ProjectX
答案 0 :(得分:2)
递归公用表表达式将遍历层次结构
with ed as (
select
employee.id, employee.managerid, department.department
from employee left join department on employee.Id = department.Id
where department is not null
union all
select
employee.id, employee.managerid, department.department
from employee
inner join ed on employee.managerid = ed.id
inner join department on ed.Id = department.Id
)
select * From ed
答案 1 :(得分:1)
select employeedata.id,name,managerId,
case when DepartmentName
is null then (select departmentName from department where id =managerID )
else DepartmentName
end as dep2
from employeeData
left join
department on employeeData.id=department.id
答案 2 :(得分:0)
这样做:
SELECT e.*,
CASE h1.Department IS NULL h2.Department ELSE h1.Department END AS Department
from employee e
LEFT JOIN heads h1 ON e.id = h1.id
LEFT JOIN heads h2 ON e.ManagerId = h2.id