-1

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

ID、名称、ManagerId

1、老板、空

2、经理A、1

3、经理B、1

4、铅C、2

5、工程师D、4

...

另一个表包含谁是每个部门的负责人

编号,部门

2、发展

3、销售

4、项目X

现在我想基于第一个表创建一个视图,但还有一个部门列,由表 2 中具有条目的最近祖先确定。是否可以使用单个 SQL 语句?

ID、姓名、经理 ID、部门

1、老大、空、空

2、经理A、1、开发

3、经理B、1、销售

4、LeadC、2、ProjectX

5,工程师D,4,ProjectX

4

3 回答 3

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/

于 2013-06-27T06:45:01.803 回答
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

见你的sql演示

于 2013-06-27T06:55:06.777 回答
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
于 2013-06-27T06:39:51.947 回答