给出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”已从新结果中删除。
答案 0 :(得分: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';
或者如果您想使用Recursive subquery factoring:
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;