Oracle树结构

qojgxg4l  于 2023-08-03  发布在  Oracle
关注(0)|答案(1)|浏览(95)

有没有可能在不使用connect by的情况下创建一个树结构,并使用oracle的分析函数,例如dense_rank?我正在尝试从Oracle HR模式重新创建此查询。

SELECT last_name, employee_id, manager_id, LEVEL
      FROM employees
      START WITH employee_id = 100
      CONNECT BY PRIOR employee_id = manager_id
      ORDER SIBLINGS BY last_name;

字符串

k5hmc34c

k5hmc34c1#

您可以使用带有SEARCH子句的递归查询来模拟带有ORDER SIBLINGS BY的分层查询:

WITH emps (last_name, employee_id, manager_id, depth) AS (
  SELECT last_name, employee_id, manager_id, 1
  FROM   employees
  WHERE  employee_id = 100
UNION ALL
  SELECT e.last_name, e.employee_id, e.manager_id, p.depth + 1
  FROM   employees e
         INNER JOIN emps p
         ON p.employee_id = e.manager_id
)
SEARCH DEPTH FIRST BY last_name SET order_id
SELECT last_name, employee_id, manager_id, depth
FROM   emps;

字符串
其中,对于样本数据:

CREATE TABLE employees (last_name, employee_id, manager_id) AS
SELECT 'Alice', 100, NULL FROM DUAL UNION ALL
SELECT 'Beryl', 101, 100 FROM DUAL UNION ALL
SELECT 'Carol', 102, 100 FROM DUAL UNION ALL
SELECT 'Debra', 103, 100 FROM DUAL UNION ALL
SELECT 'Emily', 104, 101 FROM DUAL UNION ALL
SELECT 'Fiona', 105, 104 FROM DUAL UNION ALL
SELECT 'Gerri', 106, 102 FROM DUAL UNION ALL
SELECT 'Holly', 107, 102 FROM DUAL UNION ALL
SELECT 'Irene', 108, 107 FROM DUAL UNION ALL
SELECT 'Julia', 109, 106 FROM DUAL UNION ALL
SELECT 'Kerry', 110, 104 FROM DUAL;


输出:
| 员工_ID|管理员ID|深度| DEPTH |
| --|--|--| ------------ |
| 一百| * 空 *| 一个| 1 |
| 一百零一|一百|二个| 2 |
| 一百零四|一百零一|三个| 3 |
| 一百零五|一百零四|四个| 4 |
| 一百一十|一百零四|四个| 4 |
| 一百零二|一百|二个| 2 |
| 一百零六|一百零二|三个| 3 |
| 一百零九|一百零六|四个| 4 |
| 一百零七|一百零二|三个| 3 |
| 一百零八|一百零七|四个| 4 |
| 一百零三|一百|二个| 2 |
fiddle

相关问题