2017-06-07 17 views
-1

基本的に、従業員の番号と、自分が報告する相手のemployeeNumberをリストするテーブルがあります。 SQLで従業員の上司のリストを取得する方法

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

等等だから、ドンウォンの階層は次のようになります。彼は、レポートへ -

1234(私は、SQLに新たなんだ> - への報告> 3245 - 報告> 1532へ清潔で理解しやすいソリューションが加わることにより)

+2

どのdbmsを使用していますか? – jarlh

+0

これを自分で解決しようとするときに*何らかの努力を実証することができますか? –

+0

ええと、あなたはチェーン全体が必要だと思っています...何層ですか?それとも無制限にできますか? – Sourcery

答えて

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、限り、あなたは好きなこと...しかし、プログラム的にそれを行うことは、おそらく簡単ですすることができます前に 終わり。

0

あなたはので、これはあなたが "グラフィック" の表示をしたい場合は、この(まだ標準の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

であるあなたのDBMSを指定していませんでした:

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; 
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) 
関連する問題