我在oracle中尝试Hierarchical select
查询但是不能从那里得到强烈的愿望并且不会在我写错了查询之前或者有错误在我的表中的数据我的愿望就像
I_ID NAME MGR_ID LEVEL PATH
1 SMITH 0 0 /SMITH
2 ALLEN 1 1 /SMITH/ALLEN
3 WARD 1 1 /SMITH/WARD
5 MARTIN 1 1 /SMITH/MARTIN
4 JONES 2 2 /SMITH/ALLEN/JONES
7 CLARK 2 2 /SMITH/ALLEN/CLARK
6 BLAKE 3 2 /SMITH/WARD/BLAKE
8 SCOTT 7 3 /SMITH/ALLEN/CLARK/SCOTT
9 KING 7 3 /SMITH/ALLEN/CLARK/KING
10 TURNER 8 4 /SMITH/ALLEN/CLARK/SCOTT/TURNER
12 JAMES 8 4 /SMITH/ALLEN/CLARK/SCOTT/JAMES
11 ADAMS 10 5 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS
13 FORD 11 6 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD
14 MILLER 13 7 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD/MILLER
请帮助我参考check
答案 0 :(得分:1)
我使用类似于你的查询,并将结果分组以仅为每个i_ids选择一行具有最大级别。
<强>查询强>:
select *
from (
select
i_id, name, mgr_id, max(plevel) - 1 "level",
max(path) keep (dense_rank last order by plevel) path
from (
select i_id, name, mgr_id, level plevel, SYS_CONNECT_BY_PATH(name, '/') path
from emp
connect by prior i_id = mgr_id
)
group by i_id, name, mgr_id
)
order by "level", i_id
<强> Results 强>:
| I_ID | NAME | MGR_ID | LEVEL |PATH |
|------|--------|--------|-------|--------------------------------------------------|
| 1 | SMITH | 0 | 0 |/SMITH |
| 2 | ALLEN | 1 | 1 |/SMITH/ALLEN |
| 3 | WARD | 1 | 1 |/SMITH/WARD |
| 5 | MARTIN | 1 | 1 |/SMITH/MARTIN |
| 4 | JONES | 2 | 2 |/SMITH/ALLEN/JONES |
| 6 | BLAKE | 3 | 2 |/SMITH/WARD/BLAKE |
| 7 | CLARK | 2 | 2 |/SMITH/ALLEN/CLARK |
| 8 | SCOTT | 7 | 3 |/SMITH/ALLEN/CLARK/SCOTT |
| 9 | KING | 7 | 3 |/SMITH/ALLEN/CLARK/KING |
| 10 | TURNER | 8 | 4 |/SMITH/ALLEN/CLARK/SCOTT/TURNER |
| 12 | JAMES | 8 | 4 |/SMITH/ALLEN/CLARK/SCOTT/JAMES |
| 11 | ADAMS | 10 | 5 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS |
| 13 | FORD | 11 | 6 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD |
| 14 | MILLER | 13 | 7 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD/MILLER |