用于查找每行的祖先的SQL语句

时间:2013-06-27 06:23:37

标签: sql sql-server

有两个表,一个包含分层员工数据,

  

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

3 个答案:

答案 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

回答改编自http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/

答案 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

see you sql demo

答案 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