3

给定 Oracle 11gr2 中的以下树层次结构示例:

询问:

SELECT Lpad(ename,Length(ename) + LEVEL * 10 - 10,'-') 
FROM   emp 
START WITH mgr IS NULL 
CONNECT BY PRIOR empno = mgr


Result:


KING
----------JONES
--------------------SCOTT
------------------------------ADAMS
--------------------FORD
------------------------------SMITH
----------BLAKE
--------------------ALLEN
--------------------WARD
--------------------MARTIN
--------------------TURNER
--------------------JAMES
----------SAM
--------------------MILLER

我需要修剪我的树查询,以便每当 ename 以字符 'S' 开头时i.e. substr(ename,1,1) = 'S',显示此值/分支,但随后忽略低于该值的所有内容,即在此级别之后不再显示任何内容。

因此,基于上述结果样本,新的结果样本将如下所示:

New Result:

KING
----------JONES
--------------------SCOTT
--------------------FORD
------------------------------SMITH
----------BLAKE
--------------------ALLEN
--------------------WARD
--------------------MARTIN
--------------------TURNER
--------------------JAMES
----------SAM

因此,子“ADAMS”和“MILLER”已从新结果中删除。

4

1 回答 1

3
SELECT Lpad(ename,Length(ename) + LEVEL * 10 - 10,'-') 
FROM   emp 
START WITH mgr IS NULL 
CONNECT BY PRIOR empno = mgr and substr(PRIOR ename,1,1) <> 'S';

或者,如果您想使用递归子查询分解

with employees(empno, ename, mgr, emp_level) as
(
    select empno, ename, mgr, 1 emp_level
    from emp
    where mgr is null
    union all
    select emp.empno, emp.ename, emp.mgr, emp_level+1 emp_level
    from emp
    join employees
        on emp.mgr = employees.empno
    where substr(employees.ename,1,1) <> 'S'
) search depth first by empno set order1
select Lpad(ename,Length(ename) + emp_level * 10 - 10,'-')
from employees
order by order1;

SQL小提琴

于 2013-11-01T05:02:25.040 回答