philshem
philshem

Reputation: 25331

Find the top-level parent group each record belongs to

I have hierarchical data with the following structure. The levels are 1 to 6, so instead of doing 6 joins and then coalesce, how can I find what is the top-level parent (which has no parent_nr).

enter image description here

I've tried the accepted 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
;

but it only gives me the next level as "Top Level ID" and not the final level (A)

enter image description here

Upvotes: 0

Views: 63

Answers (2)

MT0
MT0

Reputation: 167962

Oracle Setup:

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;

Query:

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;

Output:

LEVEL ROOT_CODE CODE_NR 
----- --------- ---------
    1 A         A        
    2 A         A.1      
    3 A         A.1.1    
    4 A         A.1.1.1  
    5 A         A.1.1.1.1
    4 A         A.1.1.2  
    5 A         A.1.1.2.1
    5 A         A.1.1.2.2

Upvotes: 1

nightfox79
nightfox79

Reputation: 2119

You could try the following:

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
;

Upvotes: 0

Related Questions