如何在SQL中检索Employee的上层列表

时间:2017-06-07 11:33:13

标签: sql hierarchical-data recursive-query

基本上,我有一个表格,列出员工的编号和他们向谁报告的员工编号。

 EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532

等。等等。董东的等级将是:他向 - >报告1532报告 - > 3245报告 - > 1234.

(我是SQL的新手,所以我们非常感谢干净易懂的解决方案)

3 个答案:

答案 0 :(得分:0)

通过加入......

select e1.EmpNum, e1.name, e2.EmpNum as BossNum, e2.name as BossName from empTable e1 join empTable e2 on e1.ReportsTo=e2.EmpNum

然后可以根据需要加入连接,e3,e4 ......但是以编程方式进行连接可能在前端更容易。

答案 1 :(得分:0)

您没有指定DBMS,因此这是标准的ANSI SQL

with recursive report_tree as (
  select empnum, name, reportsto
  from employees
  where empnum = 6574 
  union all
  select c.empnum, c.name, c.reportsto
  from employees c 
    join report_tree p on p.reportsto = c.empnum
) 
select *
from report_tree;

如果你想要一个"图形"显示,你可以做这样的事情(仍然是标准的ANSI SQL):

with recursive report_tree as (
  select empnum, name, reportsto, name as report_path, 1 as level
  from employee
  where empnum = 6574 
  union all
  select c.empnum, c.name, c.reportsto, p.report_path || ' -> ' || c.name, p.level + 1
  from employee c 
    join report_tree p on p.reportsto = c.empnum
) 
select *
from report_tree
order by level desc 
fetch first 1 row only;

答案 2 :(得分:0)

试试这个,cte最适合递归。对于这样的问题,已经有很多解决方案

create table #emp(
EmpNum int,
Name varchar(50),
ReportsTo int
);

insert into  #emp
values
(1234,'John',4523),
(3245,'Annie',1234),
(1532,'Bob',3245),
(6574,'Dong',1532)



with rec as (
    select #emp.ReportsTo, #emp.EmpNum, #emp.Name, 1 as level from #emp where Name = 'Bob'
    union all
    select  #emp.ReportsTo, #emp.EmpNum, #emp.Name, level + 1 as level from #emp    
    inner join rec   
    on #emp.EmpNum = rec.ReportsTo
)
select ReportsTo, EmpNum, Name, level from rec
where level = (select max(level) from rec)
OPTION (MAXRECURSION 0)