Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检索员工列表';SQL中的超级用户_Sql_Hierarchical Data_Recursive Query - Fatal编程技术网

如何检索员工列表';SQL中的超级用户

如何检索员工列表';SQL中的超级用户,sql,hierarchical-data,recursive-query,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汇报,

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

 EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532
等等等等。所以黄东的等级结构是:他向->1532汇报,哪个向->3245汇报,哪个向->1234汇报

(我是SQL新手,所以希望能有清晰易懂的解决方案)

通过加入

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。。。但是在前端以编程方式进行可能更容易。

您没有指定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):


试试这个,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)

你用的是哪种数据库管理系统?你能证明你自己在努力解决这个问题吗?嗯,我意识到你需要一个完整的链。。。有多少层?或者这可能是无限的?
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)