找到每个记录所属的顶级父组

时间:2017-05-05 09:44:28

标签: sql oracle hierarchy

我有hierarchical data具有以下结构。级别是1到6,所以我不是做6个连接然后合并,而是如何找到顶级父级(没有parent_nr)。

enter image description here

我已尝试接受answer here

SELECT
  aa.code_nr,
  aa.parent_nr,
  CONNECT_BY_ROOT aa.code_nr AS "Top Level ID"
FROM mytable_t aa
CONNECT BY PRIOR aa.code_nr = aa.parent_nr
;

但它只给了我下一个级别"顶级ID"而不是最后一级(A)

enter image description here

2 个答案:

答案 0 :(得分:1)

Oracle安装程序

   {
   "name": "debezium-connector",
   "connector": {
      "state": "RUNNING",
      "worker_id": "xx.xx.xx.xxx:8083"
   },
   "tasks": [
      {
         "state": "FAILED",
         "trace": "org.apache.kafka.connect.errors.ConnectException: Task already exists in this worker: debezium-connector-0\n\tat org.apache.kafka.connect.runtime.Worker.startTask(Worker.java:308)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.startTask(DistributedHerder.java:834)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.access$1500(DistributedHerder.java:101)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder$13.call(DistributedHerder.java:848)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder$13.call(DistributedHerder.java:844)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\n",
         "id": 0,
         "worker_id": "xx.xx.xx.xxx:8083"
      }
   ]
}

<强>查询

CREATE TABLE my_table ( code_nr, parent_nr ) AS (
  SELECT 'A', NULL FROM DUAL UNION ALL
  SELECT 'A.1', 'A' FROM DUAL UNION ALL
  SELECT 'A.1.1', 'A.1' FROM DUAL UNION ALL
  SELECT 'A.1.1.1', 'A.1.1' FROM DUAL UNION ALL
  SELECT 'A.1.1.2', 'A.1.1' FROM DUAL UNION ALL
  SELECT 'A.1.1.1.1', 'A.1.1.1' FROM DUAL UNION ALL
  SELECT 'A.1.1.2.1', 'A.1.1.2' FROM DUAL UNION ALL
  SELECT 'A.1.1.2.2', 'A.1.1.2' FROM DUAL;

<强>输出

SELECT LEVEL,
       code_nr AS root_code_nr,
       CONNECT_BY_ROOT( code_nr ) AS code_nr
FROM   my_table
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY PRIOR parent_nr = code_nr;

答案 1 :(得分:0)

您可以尝试以下方法:

SELECT
  aa.code_nr,
  aa.parent_nr,
  substr(SYS_CONNECT_BY_PATH(aa.code_nr, '/'),2,instr(SYS_CONNECT_BY_PATH(aa.code_nr, '/'),'/'))
FROM mytable_t aa
CONNECT BY PRIOR aa.code_nr = aa.parent_nr
;