2015-06-20 47 views
1

考慮以下表如何在自循環表中導航?

create table EMPLOYEE 
(
    empno NUMBER not null, 
    ename VARCHAR2(100), 
    salary NUMBER, 
    hiredate DATE, 
    manager NUMBER 
); 

alter table EMPLOYEE add constraint PK_EMP primary key (EMPNO); 

alter table EMPLOYEE 
    add constraint FK_MGR foreign key (MANAGER) 
     references EMPLOYEE (EMPNO); 

其是自循環表即每個僱員擁有管理器,除了根。

我想運行在此表下面的查詢:

找到比他們的管理者更多的薪金所有的員工?


附:

只有一個根在結構

考慮下面的查詢

SELECT LPAD(emp.ename, (LEVEL-1)*5 + LENGTH(emp.ename), ' ') AS "Hierarchy" 
    FROM employee emp 
    START WITH emp.manager IS NULL 
    CONNECT BY manager = PRIOR empno; 

結果會是這樣的:

Alice 
    Alex 
    Abbey 
Sarah 
Jack 
    Bill 
    Jacob 
    Valencia 
Bob 
    Babak 
... 

我做下面的查詢

SELECT LPAD(emp.ename, (LEVEL-1)*5 + LENGTH(emp.ename), ' ') AS "Hierarchy" 
    FROM employee emp 
    START WITH empno IN (SELECT empno FROM employee) 
    CONNECT BY PRIOR manager = empno; 

它爲員工表中的每個員工從下到上創建一個子樹,但我不知道如何瀏覽以獲得期望的結果!

+1

首先讓我們知道你已經嘗試過什麼? –

+0

經理可以在他上面有經理嗎?之後的下一個,等等?在這種情況下,你希望查詢返回什麼? (就像Deepak說的,告訴我們你到目前爲止) – sstan

+0

不,表中只有一個根 –

回答

1

這裏是做

with fullemployee (empno, ename, salary, key) 
as 
(
    select A.empno, A.ename, A.salary, A.empno || '.' from 
     employee A 
    where A.manager is null 
    union all 
    select C.empno, C.ename, C.salary, D.key || '.' || C.empno from 
     employee C 
     inner join fullemployee D on C.manager = D.empno 
) 
select E.ename, F.ename as manager from fullemployee E 
inner join fullemployee F on E.key like F.key || '%' and E.key <> F.key 
where E.salary > F.salary 

或等價

with fullemployee (empno, ename, salary, key) 
as 
(
    SELECT empno, ename, salary, SYS_CONNECT_BY_PATH(empno, '.') || '.' 
    FROM employee 
    START WITH manager is null 
    CONNECT BY PRIOR empno = manager 
) 
select E.ename, F.ename as manager from fullemployee E 
inner join fullemployee F on E.key like F.key || '%' and E.key <> F.key 
where E.salary > F.salary 

SQL小提琴的一種方式 - http://sqlfiddle.com/#!4/37f4ae/35

0

這應該做的工作。如果您不想在列表中顯示「根」,請刪除or條件。

select e.empno, e.ename, e.salary from employee e 
    inner join employee mgr on mgr.empno = e.manager 
where e.salary > mgr.salary 
or (e.manager = mgr.empno) 
+0

上述SQL代碼「找到所有比他們的經理工資更高的員工」是錯誤的! 請注意,每個經理都有一個層級的管理者,直到根,即如果A是B的經理,C是A的經理,我們也可以說C是B的經理。假設根是最低工資,所以結果集應該控制除root之外的所有人! –