connect by prior (hierarchical query)

Hi all

Some1 asked me a question that goes like this:

Source

emp_no dep_no
10 110
20 110
30 110
40 110
10 120
10 130
130 20

write a query to get the following output from the source above

emp_no dept_no
110 10203040
10 120
130 1020

Now I stumbled upon solutions with the terms "connect by front" but I'm nt able to understand how oracle produces this result, could someone point me to a good article or a text that can explain this concept very well (I searched on google and have seen many articles, but I could not able to understand since these articles were not all explain)

Concerning
Rahul

Hi, Rahul,

Welcome to the forum!

What you want to do is called chain aggregation . This page shows the different ways to do it:
http://www.Oracle-base.com/articles/10G/StringAggregationTechniques.php

SYS_CONNECT_BY_PATH (which requires a CONNECT BY query) is just a medium. (From Oracle 11.2, LISTAGG is clearly the best way to string aggregation. Before that, SYS_CONNECT_BY_PATH seems to be the most popular, especially if the results must be in order.)

The following pages are introductions to CONNECT BY queries:
http://www.adp-GmbH.ch/ora/SQL/connect_by.html
http://www.oradev.com/connect_by.jsp

Tags: Database

Similar Questions

  • Reg: Hierarchical query (using connection by)

    Hi all
    I got the result with the hierarchical query in the form:
    * / qxxh *.
    * / qxxh/jxobcbg *.
    * / qxxh/jxobcbg/n00wcp4 *.
    * / qxxh/jxobcbg/n00wcp4 / 000263 x *.
    * / qxxh/jxobcbg/n00wcp4 / x 000263 / p0263 *.
    * / qxxh/jxxocbg *.
    * / qxxh/jxxocbg/n00voc1 *.
    * / qxxh/jxxocbg/n00voc1 / x 000589 *.
    * / qxxh/jxxocbg/n00voc1 / x 000589 / p0589 *.
    * / qxxh/jxuwxxh *.
    * / qxxh/jxuwxxh/n00xpxf *.
    * / qxxh, jxuwxxh, n00xpxf, m00bxpl *.
    * / qxxh/jxuwxxh/n00xpxf/m00bxpl / 000522 x *.
    * / qxxh/jxuwxxh/n00xpxf/m00bxpl / 000522 x / p0522 *.

    Here, I want to select only the maximum path. Here I used "SYS_CONNECT_BY_PATH.
    Please let meknow how to do this?
    Thanks in advance.

    Published by: udeffcv on December 9, 2009 22:03

    udeffcv wrote:
    Hi all
    I got the result with the hierarchical query in the form:
    * / qxxh *.
    * / qxxh/jxobcbg *.
    * / qxxh/jxobcbg/n00wcp4 *.
    * / qxxh/jxobcbg/n00wcp4 / 000263 x *.
    * / qxxh/jxobcbg/n00wcp4 / x 000263 / p0263 *.
    * / qxxh/jxxocbg *.
    * / qxxh/jxxocbg/n00voc1 *.
    * / qxxh/jxxocbg/n00voc1 / x 000589 *.
    * / qxxh/jxxocbg/n00voc1 / x 000589 / p0589 *.
    * / qxxh/jxuwxxh *.
    * / qxxh/jxuwxxh/n00xpxf *.
    * / qxxh, jxuwxxh, n00xpxf, m00bxpl *.
    * / qxxh/jxuwxxh/n00xpxf/m00bxpl / 000522 x *.
    * / qxxh/jxuwxxh/n00xpxf/m00bxpl / 000522 x / p0522 *.

    Here, I want to select only the maximum path. Here I used "SYS_CONNECT_BY_PATH.
    Please let meknow how to do this?
    Thanks in advance.

    Published by: udeffcv on December 9, 2009 22:03

    What do you mean by maximum path? is this...
    * / qxxh/jxobcbg/n00wcp4 / x 000263 / p0263 *.
    * / qxxh/jxxocbg/n00voc1 / x 000589 / p0589 *.
    * / qxxh/jxuwxxh/n00xpxf/m00bxpl / 000522 x / p0522 *.

    is it child nodes?
    so, you would like to see
    Column nickname... CONNECT_BY_ISLEAF example, you can find it in the link below
    http://download.Oracle.com/docs/CD/B14117_01/server.101/b10759/pseudocolumns001.htm#sthref670

    Ravi Kumar

  • Connect By hierarchical query clause-

    Hello

    I wrote a query using the Connect By clause to generate the table data structure tree with appropriate levels.

    But given could not correct as there may be data that did the trick. As Table1 is parent from table 2 and table 2 is parent from table 3 and table 3 is again Parent from table 1. If these incorrect data then I get error Oracle "ORA-01436: CONNECT loop in the user data" which is correct.

    What I need is, whenever this error message is triggered I give my own error instead of this Oracle error message in the SQL statement. Please note that I do not use any PLSQL block, I have just one SQL statement. Appreciate any help on this topic. Thank you.

    Hello

    Outside of PL/SQL, I don't know anyway to substitute your own error messages for those that oracle provides.

    In Oracle 10 (and more), you can write a query using the CONNECT_BY_ISCYCLE pseudo-column. Using CONNECTION BY NOCYCLE, the query will never actually throw the error ORA-01436, but you can get it to display your message in the case there, you not used CONNECT BY NOCYCLE.

    Here's how:
    Equip your actual query, CONNECT_BY_ISCYCLE, the WITH clause.
    Get this subquery (CONNECT_BY_ISCYCLE) MAX. We'll call this max_cbi.
    Do a UNION ALL of two pins:
    (1) selects everything (except, pehaps, CONNECT_BY_ISCYCLE), subquery, WHERE max_cbi = 0
    (2) allows you to select your 'error message' double, WHERE max_cbi = 1.

    Published by: Frank Kulash, November 26, 2008 14:09

  • Query on hierarchical query in interactive report!

    Hello

    In Apex Oracle 5.1, I tried to use an interactive report to view details of employee based on a hierarchy. I used the query to display data below:

    SELECT last_name, employe_id, manager_id, LEVEL

    Employees

    START WITH employee_id = 100

    CONNECT BY PRIOR employee_id = manager_id

    Brothers and SŒURS of ORDER BY last_name;

    The output was as below:

    LAST_NAME EMPLOYEE_ID MANAGER_ID LEVEL

    ------------------------- ----------- ---------- ----------

    King                                100                                                       1

    Cambrault                        148                                 100                 2

    Bates                              172                                 148                 3

    Bloom                             169                                  148                3

    Fox                                 170                                  148                3

    Kumar                             173                                  148                3

    Ozer                                168                                  148               3

    Smith                               171                                  148              3

    De Haan                           102                                   100             2

    Hunold                              103                                   102             3

    Austin                               105                                   103             4

    Ernst                                 104                                   103             4

    Lorentz                              107                                   103             4

    Pataballa                           106                                    103            4

    Errazuriz                           147                                   100              2

    Ande                                 166                                    147             3

    Banda                               167                                     147             3

    ...

    Now, I would like to display data based on the connection of employees.

    For example (based on above request): If an employee named - Cambrault is the login, only employees under him (Bates, Bloom, Fox, Kumar, Smith, Ozer) and its own contact information should appear in the report.

    Please advise.

    Kind regards

    mebu

    Mebu wrote:

    I used a hierarchical query. But based on Login, I want to display only members under him.

    For example: If Cambrault LOGIN, only employees under him (Bates, Bloom, Fox, Kumar, Smith, Ozer) and its own coordinates must display in Oracle Apex.

    SELECT last_name, employe_id, manager_id, LEVEL

    Employees

    START WITH employee_id = 100

    CONNECT BY PRIOR employee_id = manager_id

    Brothers and SŒURS of ORDER BY last_name;

    See what/when/where? How to get the answers from the forum

    Describe the requirements clearly and completely, using the APEX, Oracle and terminology of web standard.

  • hierarchical query of VO in the ofa page

    Hello

    I try to use the hierarchical query in VO for the display of all levels of supervisors for employee and want to display in populist:

    This is the query

    REPLACE SELECT distinct (mgx.full_name, "',' ') supervisor_full_name;

    XPP. Employee_number

    OF per_assignments_x pax,.

    per_people_x ppx,

    per_people_x mgx,

    per_positions pp,

    per_jobs pj,

    per_position_definitions ppd

    WHERE ppx.person_id = pax.person_id

    AND ppx.current_employee_flag = 'Y '.

    AND mgx.person_id = pax.supervisor_id

    AND pp.position_id = pax.position_id

    AND pj.job_id = pax.job_id

    AND ppd.position_definition_id = pp.position_definition_id

    START WITH ppx.employee_number =: 1

    CONNECT BY PRIOR MGX.employee_number = ppx.employee_number AND LEVEL < 6

    I'm trying to get this VO implemented PR when I run the page in jdeveloper with parameter binding, it's getting error.

    oracle.apps.fnd.framework.OAException: oracle.jbo.SQLStmtException: 27122 Houston: SQL error in the preparation of the statement.

    I would like to delete the parameter binding and executing CO VO past these two statements may be:

    START WITH ppx.employee_number =: 1

    CONNECT BY PRIOR MGX.employee_number = ppx.employee_number AND LEVEL < 6

    How can I do?

    Thank you

    MK

    has worked?

  • Fill out the "limits" for nodes in a hierarchical query

    Hello

    I have a table called V that is organized hierarchically. You can have a "hierarchical" view by issuing the following query (PARENT_ID NULL is the root):

    SELECT rn, 
           LPAD ('_ ', 2 * (LEVEL - 1), '_ ') || id tree,
           id, 
           parent_id, 
           lvl, 
           cbi, 
           tree_lft, 
           tree_rgt, 
           tl, 
           tr 
    FROM v
    START WITH parent_id IS NULL 
    CONNECT BY PRIOR id = parent_id
    ORDER SIBLINGS BY rn;
    

    Now, my task is to fill in the TL and TR "limits" that define the beginning and end of each group under all nodes.

    For a better understanding, I've already placed the expected results in the TREE_LFT and TREE_RGT columns. The hierarchy follows the order of the columns, RN.

    TREE_LFT begins with the root (RN = 1) line 1 and lights up gradually until it reaches the leaves (CBI = 1). If a sheet is found, TREE_RGT is set to + 1 TREE_LFT.

    Then, if another sheet follows (online RN = 4), it takes the next increment TREE_LFT + 1. And so on. When all the leaves under the node assigned a value for TREE_LFT and TREE_RGT,

    the TREE_RGT value for the node takes the last value assigned to its + 1 children. For example, you can see that the children of the node id = 14 come from RN = RN = 30 3. The value of TREE_RGT

    for the last child (RN = 30) is 58, so the TREE_RGT value for the node id = 14 will be 58 + 1 = 59.

    Then the numbering continues gradually for the rest of the hierarchy. There is a new node to RN = 31, so TREE_LFT starts from TREE_RGT of the previous node + 1, that is, 60.

    This logic continues until the end of the hierarchy following RN.

    Using a STANDARD clause, I've managed to fill TL (you can see TL = TREE_LFT) and TR for the leaves.

    I also managed to complete the TR for nonleaf with a second MODEL clause, but it runs very bad when the array is much more filled than that.

    This is the STANDARD clause that allows you to calculate the TR:

    select *
    from v
    model 
    dimension by (id, parent_id, cbi)
    measures (rn, tree_lft, tree_rgt, lvl, tl, tr)
    rules (
           tr[ANY, ANY, 0] order by lvl desc, id, parent_id = max(tr)[ANY, CV(id), ANY] + 1
          )
          ;
    

    It does the job as expected, but the generic as well as ordered rule is a killer when it is applied to a larger painting.

    So my question is, is there a way I can write a query that would do the same as this one, but with better performance (functions analytical pattern)?

    I know that I can not really clear that it is not easy to explain.

    I use a database with 11.2.0.3 Enterprise Edition.

    Thank you

    Here are the scripts to test:

    create table v (RN NUMBER, NUMBER identification, PARENT_ID NUMBER, TREE_LFT NUMBER, TREE_RGT NUMBER, CBI NUMBER, NUMBER of LVL, TL NUMBER, NUMBER of TR);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (1, 3, null, 1, 100, 0, 1, 1, null);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (2, 14, 3, 2, 59, 0, 2, 2, null);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (3, 224, 14, 3, 4, 1, 3, 3, 4);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (4, 221, 14, 5, 6, 1, 3, 5, 6);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (5, 236, 14, 7, 8, 1, 3, 7, 8);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (6, 218, 14, 9, 10, 1, 3, 9, 10);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (7, 230, 14, 11, 12, 1, 3, 11, 12);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (8, 234, 14, 13, 14, 1, 3, 13, 14);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (9, 235, 14, 15, 16, 1, 3, 15, 16);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (10, 253, 14, 17, 18, 1, 3, 17, 18);

    insert into v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) values (11, 245, 14, 19, 20, 1, 3, 19, 20);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (12, 231, 14, 21, 22, 1, 3, 21, 22);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (13, 228, 14, 23, 24, 1, 3, 23, 24);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (14, 243, 14, 25, 26, 1, 3, 25, 26);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (15, 219, 14, 27, 28, 1, 3, 27, 28);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (16, 220, 14, 29, 30, 1, 3, 29, 30);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (17, 229, 14, 31, 32, 1, 3, 31, 32);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (18, 248, 14, 33, 34, 1, 3, 33, 34);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (19, 244, 14, 35, 36, 1, 3, 35, 36);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (20, 254, 14, 37, 38, 1, 3, 37, 38).

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (21, 247, 14, 39, 40, 1, 3, 39, 40);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (22, 225, 14, 41, 42, 1, 3, 41, 42);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (23, 226, 14, 43, 44, 1, 3, 43, 44).

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (24, 249, 14, 45, 46, 1, 3, 45, 46);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (25, 250, 14, 47, 48, 1, 3, 47, 48);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (26, 252, 14, 49, 50, 1, 3, 49, 50);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (27, 251, 14, 51, 52, 1, 3, 51, 52);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (28, 246, 14, 53, 54, 1, 3, 53, 54);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (29, 256, 14, 55, 56, 1, 3, 55, 56);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (30, 255, 14, 57, 58, 1, 3, 57, 58);

    insert into v values (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (31, 15, 3, 60, 75, 0, 2, 60, null);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (32, 222, 15, 61, 62, 1, 3, 61, 62);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (33, 223, 15, 63, 64, 1, 3, 63, 64);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (34, 241, 15, 65, 66, 1, 3, 65, 66);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (35, 242, 15, 67, 68, 1, 3, 67, 68);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (36, 227, 15, 69, 70, 1, 3, 69, 70);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (37, 213, 15, 71, 72, 1, 3, 71, 72);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (38, 214, 15, 73, 74, 1, 3, 73, 74);

    insert into v values (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (39, 16, 3, 76, 81, 0, 2, 76, null);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (40, 238, 16, 77, 78, 1, 3, 77, 78);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (41 237, 16, 79, 80, 1, 3, 79, 80);

    insert into v values (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (42, 17, 3, 82, 85, 0, 2, 82, null);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (43, 239, 17, 83, 84, 1, 3, 83, 84);

    insert into v values (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (44, 18, 3, 86, 99, 0, 2, 86, null);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (45, 232, 18, 87, 88, 1, 3, 87, 88);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (46, 233, 18, 89, 90, 1, 3, 89, 90);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (47, 215, 18, 91, 92, 1, 3, 91, 92);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (48, 216, 18, 93, 94, 1, 3, 93, 94);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (49, 217, 18, 95, 96, 1, 3, 95, 96);

    insert into values of v (RN, ID, PARENT_ID, TREE_LFT, TREE_RGT, CBI, LVL, TL, TR) (50, 240, 18, 97, 98, 1, 3, 97, 98);

    Hi Greg,.

    It looks like you use the defined nested data model.

    See solutions mentioned above:

    https://community.Oracle.com/thread/2603314 (last post)

    https://community.Oracle.com/message/12468999#12468999

  • Help with hierarchical query

    I'm trying to parse each string inside of individual characters. For this, I used the link by the hierarchical query clause. I am not able to use connect by correctly. Here is my example.

    with the CBC as)

    Select 1: the nurse, 'abc' double union all Str

    Select 2: the nurse, '123' Str of all union double

    Select 3: the nurse, "pqr xyz" dual union all Str

    Select option 4: the nurse, 'john doe' double Str

    )

    Select the level, homobasidiomycetes, substr(s.str,level,1) as chr

    s of the CBC

    connect nocycle level < = length (homobasidiomycetes)

    /

    The above query returns 3 028 lines when I want that 21. Adding a distinct to select, it's what I want.

    with the CBC as)

    Select 1: the nurse, 'abc' double union all Str

    Select 2: the nurse, '123' Str of all union double

    Select 3: the nurse, "pqr xyz" dual union all Str

    Select option 4: the nurse, 'john doe' double Str

    )

    Select distinct level, homobasidiomycetes, substr(s.str,level,1) as chr

    s of the CBC

    connect nocycle level < = length (homobasidiomycetes)

    order by str, level

    /

    For a large data set I could end up with several million rows before the separate would lead. So, how can I restrict the connection by clause to go within each line.

    Assuming that the AI is the primary key, you could do this:

    with src as (
      select 1 as rn, 'abc' as str from dual union all
      select 2 as rn, '123' as str from dual union all
      select 3 as rn, 'pqr xyz' as str from dual union all
      select 4 as rn, 'john doe' as str from dual
    )
    select level,
          s.str,
          substr(s.str,level,1) as chr
    from src s
    connect by level <= length(s.str)
              and prior rn = rn
              and prior dbms_random.value is not null;
    

    See DBMS_RANDOM.value in a hierarchical solution for string to table? for an exchange of views around the case.

  • Connect by PRIOR vrs Connect by LEVEL

    Hello

    I'm trying to understand the difference between CONNECT BY PRIOR and CONNECT BY LEVEL

    I know that CONNECT BY PRIOR is basically specifying a hierarchy and which column / field is the parent (using the PRIOR)

    for example

    SELECT employe_id, employee_name, level

    Employees

    CONNECT BY PRIOR employee_id = manager_id;


    Q1. What is CONNECT BY LEVEL (for example as shown below) practice? What type of relationship normally described? (below, it is just producucing a series of integers)

    SELECT the level

    OF the double

    CONNECT BY LEVEL < = 10;

    T2. Use LEVEL with CONNECT BY in this way, a subversive use of the CONNECT IN knowledge is really intended to be used this way?

    any advice appreciated,

    Jim

    Hi, Jim,.

    Jimbo wrote:

    Hello

    I'm trying to understand the difference between CONNECT BY PRIOR and CONNECT BY LEVEL

    I know that CONNECT BY PRIOR is basically specifying a hierarchy and which column / field is the parent (using the PRIOR)

    for example

    SELECT employe_id, employee_name, level

    Employees

    CONNECT BY PRIOR employee_id = manager_id;

    Sometimes, CONNECT BY using hierarchical data, such as a tree.  In these cases, it may be useful to use the terns as "parent" and "child."  The query above is one of these cases.

    In more general terms, CONNECT BY returns the union (UNION ALL, specifically) of lines found by the START WITH clause (LEVEL = 1) and lines found by the clause CONNECT BY (LEVEL > 1).  If there is no START WITH clause, every row in the table will appear on LEVEL = 1.

    If there is no line on LEVEL = N, then Oracle research lines that meet the CONNECT BY clause, to search for the lines that are connected to each line level = N, for put the LEVEL N + 1.  If the CONNECT BY clause is set to TRUE for a given row, while the rank will appear on level N + 1 =.  Often (but not always) the CONNECT BY clause uses the PRIOR operator.  After PRIOR consent refers to something = N level.

    Q1. What is CONNECT BY LEVEL (for example as shown below) practice? What type of relationship normally described? (below, it is just producucing a series of integers)

    SELECT the level

    OF the double

    CONNECT BY LEVEL<>

    Since there is no START WITH clause, each line of the double table will be LEVEL = 1.

    The CONNECT BY clause means that CONNECT BY always means: If there is a line at = N, then it will be connected to any line that fills the CONNECT BY conditions.

    So that the lines will be added to the level = 2?  All the lines where condition 2<= 10="" is="" true,="" so="" every="" row="" in="" the="" dual="" table="" will="" be="" on="" level="">

    What lines will be added to the level = 3?  All the lines where condition 3<= 10="" is="" true,="" so="" every="" row="" in="" the="" dual="" table="" will="" be="" on="" level="">

    ...

    What lines will be added to the level = 10?  All the lines where the condition of 10<= 10="" is="" true,="" so="" every="" row="" in="" the="" dual="" table="" will="" be="" on="" level="10." 10="" is="" true,="" so="" every="" row="" in="" the="" dual="" table="" will="" be="" on="" level="">

    What lines will be added to the level = 11?  All the lines where condition 11<= 10="" is="" true,="" so="" no="" row="" in="" the="" dual="" table="" will="" be="" on="" level="">

    Since no rows are added to the LEVEL = 11, CONNECT BY query stop right there.

    Q2. Use LEVEL with CONNECT BY in this way, a subversive use of the CONNECT IN knowledge is really intended to be used this way?

    You can think of it as being subversive.  It was certainly not how planners and the deveopers at Oracle for CONNECT BY work in versions 2 to 8; you got an error if you tried in these versions.  It is also an exception to the rule that no line can be his own ancestor.

  • Hierarchical query result

    Dear all

    I use Oracle Database 10g and I need a hierarchical query giving following release

    KING

    | __JONES

    |   | __SCOTT

    |   | __ADAMS

    |   | __FORD

    |      | __SMITH

    | __BLAKE

    |   | __ALLEN

    |   | __WARD

    |   | __MARTIN

    |   | __TURNER

    |   | __JAMES

    | __CLARK

    | __MILLER

    Best regards

    Try this

    SELECT CASE WHEN level > 1 THEN LPAD (': _ ', LEVEL,' |) ')

    END | Ename AS ename_tree

    WCP

    START WITH mgr IS NULL

    CONNECT BY PRIOR empno = mgr;

  • How to write a hierarchical query so that only the child nodes are displayed?

    Hi all

    I have a hierarchical query that I use in an area of tree demand APEX and there are nodes that have no children and I am trying to find a way to not display these nodes. Essentially if the user does not have to develop a lot of knots to know that nothing exists at the most detailed level.

    The data are based on the Oracle Fusion FND tables but for example purposes here is enough data to illustrate my question:


    create table APPL_TAXONOMY_HIERARCHY (SOURCE_MODULE_ID varchar2(30), TARGET_MODULE_ID varchar2(30));
    create table APPL_TAXONOMY_TL (module_id varchar2(30), description varchar2(100), user_module_name varchar2(30), language varchar2(5));
    create table APPL_TAXONOMY (MODULE_ID    varchar2(30),    MODULE_NAME    varchar2(30), MODULE_TYPE varchar2(10),    MODULE_KEY varchar2(30));
    create table TABLES (table_name varchar2(30), module_key varchar2(30));
    
    

    insert into APPL_TAXONOMY_TL values ('1', null, 'Oracle Fusion', 'US' );
    insert into APPL_TAXONOMY_TL values ('2', null, 'Financials', 'US' );
    insert into APPL_TAXONOMY_TL values ('3', null, 'Human Resources', 'US' );
    insert into APPL_TAXONOMY_TL values ('20', null, 'Accounts Payable', 'US' );
    insert into APPL_TAXONOMY_TL values ('10', null, 'General Ledger', 'US' );
    
    insert into APPL_TAXONOMY_HIERARCHY values ('1', 'DDDDDDDD');
    insert into APPL_TAXONOMY_HIERARCHY values ('2', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('3', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('4', '1');
    insert into APPL_TAXONOMY_HIERARCHY values ('10', '2');
    insert into APPL_TAXONOMY_HIERARCHY values ('20', '2');
    
    insert into APPL_TAXONOMY values ('1', 'Fusion', 'PROD', 'Fusion');
    insert into APPL_TAXONOMY values ('2', 'Financials', 'FAMILY', 'FIN');
    insert into APPL_TAXONOMY values ('10', 'GL', 'APP', 'GL');
    insert into APPL_TAXONOMY values ('3', 'Human Resources', 'FAMILY', 'HR');
    insert into APPL_TAXONOMY values ('20', 'AP', 'APP', 'AP');
    
    insert into tables values ('GL_JE_SOURCES_TL','GL');
    insert into tables values ('GL_JE_CATEGORIES','GL');
    

    My hierarchical query is as follows:

    with MODULES as
    (
    SELECT h.source_module_id, b.user_module_name, h.target_module_id
          FROM APPL_TAXONOMY_HIERARCHY H,
          APPL_TAXONOMY_TL B,
    APPL_TAXONOMY VL
    where H.source_module_id = b.module_id
    and b.module_id = vl.module_id
    and vl.module_type not in ('PAGE', 'LBA')
    UNION ALL
    select distinct table_name, table_name,  regexp_substr(table_name,'[^_]+',1,1) 
    from TABLES --needed as a link between TABLES and APPL_TAXONOMY
    union all
    select module_key as source_module_id, module_name as user_module_name, module_id as target_module_id  from appl_taxonomy VL where VL.module_type = 'APP')
    SELECT  case when connect_by_isleaf = 1 then 0
                when level = 1             then 1
                else                           -1
           end as status,
    LEVEL,
    user_module_name as title,
    null as icon,
    ltrim(user_module_name, ' ') as value,
    null as tooltip,
    null as link
          FROM MODULES
          START WITH source_module_id = '1'
          CONNECT BY PRIOR source_module_id = target_module_id
    ORDER SIBLINGS BY user_module_name;
    

    In Oracle APEX, this gives a tree with the appropriate data, you can see here:

    https://Apex.Oracle.com/pls/Apex/f?p=32581:29 (username: guest, pw: app_1000);

    The SQL of the query results are:

    STATUSTITLE LEVELVALUE

    ---------- ---------- ------------------------------ ------------------------------

    11 oracle FusionOracle Fusion
    -12 financial tablesFinancials
    -13 accounts payableAccounts payable
    04 APAP
    -1General Accounting 3General Accounting
    -14 GLGL
    05 GL_JE_CATEGORIESGL_JE_CATEGORIES
    05 GL_JE_SOURCES_TLGL_JE_SOURCES_TL
    02 human resourcesHuman resources

    The lowest level is the name of the table to level 5. HR is not any level under level 2, in the same way, "AP" (level 4) has nothing below, i.e. no level 5 and that's why I don't want to show these nodes. Is this possible with the above query?

    Thanks in advance for your suggestions!

    John

    Hello

    The following query will include only the nodes of level = 5 and their ancestors (or descendants):

    WITH modules LIKE

    (

    SELECT h.source_module_id

    b.user_module_name AS the title

    h.target_module_id

    To appl_taxonomy_hierarchy:

    appl_taxonomy_tl b

    appl_taxonomy vl

    WHERE h.source_module_id = b.module_id

    AND b.module_id = vl.module_id

    AND vl.module_type NOT IN ('PAGE', "LBA")

    UNION ALL

    SELECT DISTINCT

    table-name

    table_name

    , REGEXP_SUBSTR (table_name, ' [^ _] +')

    From the tables - required as a link between the TABLES and APPL_TAXONOMY

    UNION ALL

    SELECT module_key AS source_module_id

    AS user_module_name module_name

    module_id AS target_module_id

    Of appl_taxonomy vl

    WHERE vl.module_type = 'APP '.

    )

    connect_by_results AS

    (

    SELECT THE CHECK BOX

    WHEN CONNECT_BY_ISLEAF = 1 THEN 0

    WHEN LEVEL = 1 THEN 1

    OF ANOTHER-1

    The END as status

    LEVEL AS lvl

    title

    -, NULL AS icon

    , LTRIM (title, "") AS the value

    -, NULL as ToolTip

    -, Link AS NULL

    source_module_id

    SYS_CONNECT_BY_PATH (source_module_id - or something unique

    , ' ~' - or anything else that may occur in the unique key

    ) || ' ~' AS the path

    ROWNUM AS sort_key

    Modules

    START WITH source_module_id = '1'

    CONNECT BY PRIOR Source_module_id = target_module_id

    Brothers and SŒURS of ORDER BY title

    )

    SELECT the status, lvl, title, value

    -, icon, tooltip, link

    OF connect_by_results m

    WHEN THERE IS)

    SELECT 1

    OF connect_by_results

    WHERE the lvl = 5

    AND the path AS ' % ~' | m.source_module_id

    || '~%'

    )

    ORDER BY sort_key

    ;

    You may notice that subqueries modules and the connect_by_results are essentially what you've posted originally.  What was the main request is now called connect_by_results, and it has a couple of additional columns that are necessary in the new main request or the EXISTS subquery.

    However, I am suspicious of the 'magic number' 5.  Could you have a situation where the sheets you are interested in can be a different levels (for example, some level = 5 and then some, into another branch of the tree, at the LEVEL = 6, or 7 or 4)?  If so, post an example.  You have need of a Query of Yo-Yo, where you do a bottom-up CONNECT BY query to get the universe of interest, and then make a descendant CONNECT BY query on this set of results.

  • Summarize the costs with hierarchical query

    Hello Oracle experts! I need some advice because I am very new to the hierarchical queries really new to Oracle. I have the following table:

    CREATE TABLE routes

    (

         from  VARCHAR2(15),

         to  VARCHAR2(15),

         cost NUMBER

    );

    INSERT INTO routes VALUES('San Francisco', 'Denver', 1000);

    INSERT INTO routes VALUES('San Francisco', 'Dallas', 10000);

    INSERT INTO routes VALUES('Denver', 'Dallas', 500);

    INSERT INTO routes VALUES('Denver', 'Chicago', 2000);

    INSERT INTO routes VALUES('Dallas', 'Chicago', 600);

    INSERT INTO routes VALUES('Dallas', 'New York', 2000);

    INSERT INTO routes VALUES('Chicago', 'New York', 3000);

    INSERT INTO routes VALUES('Chicago', 'Denver', 2000);

    I want to calculate the costs through the hierarchy, to get the following result:

    FROM            TO             COST

    --------------- --------------- -----

    San Francisco Dallas   10000   //San Francisco -> Dallas

    San Francisco Denver 1000    //San Francisco -> Denver

    San Francisco Chicago   10600   //San Francisco -> Dallas -> Chicago (10000 + 600)

    San Francisco New York   12000   //San Francisco -> Dallas -> New York (10000 + 200)

    San Francisco Chicago   3000    //San Francisco -> Denver -> Chicago (1000 + 2000)

    San Francisco Dallas   1500    //San Francisco -> Denver -> Dallas (1000 + 500)

    etc..

    I from imagined using the CONNECT BY PRIOR statement to get the hierarchy and have written a query that runs through him:

    SELECT CONNECT_BY_ROOT from, to

    FROM routes

      CONNECT BY NOCYCLE PRIOR to = from;

    But I have absolutely no idea how summarize right costs, I could use some help.

    Thank you for your advice.

    Hello

    Here's a way

    SELECT DISTINCT

    CONNECT_BY_ROOT from_city AS from_city

    to_city

    , SYS_CONNECT_BY_PATH (to_city, '->') is ARRESTED - if wanted

    , XMLQUERY (SYS_CONNECT_BY_PATH (cost, '+'))

    BACK CONTENT

    ) .getnumberval () SUCH as total_cost

    CHANNELS

    WHERE CONNECT_BY_ROOT from_city <> to_city

    CONNECT BY NOCYCLE from_city = to_city PRIOR

    ORDER BY from_city

    to_city

    stops

    ;

    FROM and TO are the keywords of the Oracle, they really ugly column names.  I have changed the from_city and to_city.

  • Support for hierarchical query

    Hi all

    I must be tired and can't think clearly, so I am a little confused the following query.

    The environment is Oracle 9i:

    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64 bit Production

    PL/SQL Release 9.2.0.8.0 - Production

    CORE Production 9.2.0.8.0

    AMT for HP - UX: 9.2.0.8.0 - Production Version

    NLSRTL Version 9.2.0.8.0 - Production

    Suppose I have the following data:

    with mydata as

    (

    Select the code 1, code_high, null, 'John' cname 'Smith' csurname, 'X' union resp. double all the

    Select 2 code, 1 code_high, cname 'Bill', 'White' csurname, RESP null in union double all the

    Select 3 code, code_high 2, 'Fred' cname 'Reed' csurname, 'X' union resp. double all the

    Select 4 code, code_high, null, 'Tim' cname 'Hackman' csurname, 'X' union resp. double all the

    Select code 5, code_high 4, 'John', 'Reed' cname csurname resp null in union double all the

    Select 6 code, code_high 5, cname 'Bill', 'Hakcman' csurname, 'X' union resp. double all the

    Select the code 7, code_high 6, cname 'Fred' csurname 'White', null union resp. double all the

    Select code 8, code_high 7, 'Bill' cname 'Smith' csurname, resp. union null double all the

    Select 9 code, code_high 8, cname "Tom", "Reed" csurname, null double RESP

    )

    Select *.

    of mydata;

    CODE CODE_HIGH CNAME CSURNAME RESP

    ---------- ---------- ----- -------- ----

    John Smith 1 X

    2 1 bill White

    3 2 Fred Reed X

    4 Tim Hackman X

    5 4 John Reed

    6 5 bill Hakcman X

    7 6 Fred white

    8 7 bill Smith

    9 8 Tom Reed

    It is a hierarchical query where code_high represents the father.

    I need to find in the hierarchy of higher level responsible for each code.

    Suppose I want to find in the hierarchy, one with resp = 'X '.

    Run the following query I find for the code = 9

    Select phone, cname, csurname code

    of mydata

    When resp = 'X '.

    and rownum = 1

    Connect prior code_high = code

    start with code = 9;

    CODE CNAME CSURNAME

    ---------- ----- --------

    Bill 6 Hakcman

    Is there a way to get the full list with the loaded correspondents.

    The expected results are:

    CODE CODE_HIGH CNAME CSURNAME RESP. RESP_CODE RESP_NAME RESP_SURNAME

    ---------- ---------- ----- -------- ---- --------- --------- ------------

    1 John Smith John Smith 1 X

    2 1 bill White 1 John Smith

    3 2 Fred Reed X 3 Fred Reed

    Tim Hackman 4 X 4 Tim Hackman

    5 4 John Smith 4 Tim Hackman

    6 5 bill Hakcman Bill Hakcman 6 X

    7 6 Fred White 6 Bill Hakcman

    8 7 bill Smith 6 Bill Hakcman

    9 8 Tom Reed 6 Bill Hakcman

    Kind regards.

    Alberto

    Hi, Alberto.

    I know that you are using Oracle 9; That's why I mentioned that you would have to use a substitute for CONNECT_BY_ROOT.  Before I could show how, I saw the solution of the Padders, which is probably simpler and more efficient for this work.  Padders used REGEXP_SUBSTR, which is not available in Oracle 9, but you can use SUBSTR and INSTR instead.

    Here is the solution of the Padders for Orcle 9:

    WITH got_resp_path AS

    (

    SELECT m.*

    RTRIM (SYS_CONNECT_BY_PATH (CASE

    WHEN resp = 'X '.

    THEN the code

    END

    , ' '

    )

    ) AS resp_path

    OF mydata m

    START WITH code_high IS NULL

    CONNECT BY code_high = code PRIOR

    )

    C. SELECT

    r.code AS resp_code

    r.cname AS resp_name

    r.csurname AS resp_surname

    OF got_resp_path c

    JOIN mydata r ON r.code = TO_NUMBER (SUBSTR (c.resp_path

    INSTR (c.resp_path

    , ' '

    -1

    )

    )

    )

    ORDER BY c.code

    ;

    I agree that what you posted in your last post is not very satisfactory.  Rather than make a CONNECT a separate query for each column of resp_ you want to view, you can modify it to get only the unique code and then use it in a join, as Padders, to get all the other columns you need.

  • Hierarchical data, how to aggregate over levels in hierarchical query?

    Hello

    I hope someone can help me.

    I held in a data table ("" what part was built in what other part of when when? "')
    ID parent_id build_in build_out
    1 NULL NULL NULL
    2/1 2010 2012
    3 2 2011 2013
    4 2 2013 NULL

    What are the parts is stored in a separate table.

    Now I want to know when when which part was built in the first level, in the example, I want to know that
    1 was simply a part of 1
    2 was part of 1 between 2010 and 2012
    3 was part of 1 between 2011 and 2012
    4 has never been a part of 1

    I tried several approaches - if there is a fixed number of levels between the types, I am interested I can do using joins and more/less (similarly as some nvl). Unfortunately this is not always the case (some parts appear on several levels).
    If I'm only interested in the parts that are never deleted, I can get by using a style of connect request and get the current configuration. But I can't seem to understand the time connecting part to the high level in such a query, or even filtering absurd combinations (like "4 in 1" in the example above). I could deal with the data recovered outside the database, but I prefer not.

    Is there a way to obtain the hierarchical data with an aggregate (min, max) for all levels?

    What version of Oracle you are on?

    In 11.2.x, you can use the recursive subquery factoring. Something like

    with t (id, parent_id, build_in, build_out) as (
    select 1, null, null, null from dual union all
    select 2, 1, 2010, 2012 from dual union all
    select 3, 2, 2011, 2013 from dual union all
    select 4, 2, 2013, null from dual
    )
    , c1 (root_id, id, parent_id, build_in, build_out) as (
    select id, id, parent_id, 0, 9999
    from t
    where parent_id is null
    union all
    select root_id, t.id, t.parent_id
    , greatest(nvl(t.build_in,0), nvl(b.build_in,0))
    , least(nvl(t.build_out,9999), nvl(b.build_out,9999))
    from c1 b, t
    where b.id = t.parent_id
    )
    select * from c1
    where build_in < build_out
    ;
    ROOT_ID ID    PARENT_ID  BUILD_IN  BUILD_OUT
    ------- ----- ---------- --------- ----------
    1       1                0         9999
    1       2     1          2010      2012
    1       3     2          2011      2012      
    

    With a hierarchical query by using the syntax connection, you could do something like

    select * from (
    select connect_by_root id as root, id
    , greatest(nvl(build_in,0), nvl(prior build_in,0)) as max_in, least(nvl(build_out,9999), nvl(prior build_out,9999)) as min_out
    from t
    start with parent_id is null
    connect by parent_id = prior id
    )
    where max_in < min_out
    ;
    

    but it is not powerful enough. This version compares the dates between a current and previous levels, but the recursive subquery is to compare the dates in the current level for the winners of the comparisons to the previous level. Not sure if it's an important distinction for your needs, however.

    If you are on 11.2 I advise to use the recursive subquery factoring. If this isn't the case, you can try the link by version.

    Kind regards
    Bob

  • Problems with views based on a hierarchical query

    Datamodeler 3.1.3.706 (SQL Dev 3.2.10.09):

    When you create a view that uses a hierarchical query, the query designer encounter various difficulties:

    When pasting in the SQL code, if the notice is registered without first clicking the schema update button, the object in the entity-relationship diagram view provides a faithful representation of the view without errors, but when the reopening of the view, the code is missing.

    Simple example with the classic emp table:
    SELECT level lev
          , emp.*
       FROM emp
      CONNECT BY prior empno = mgr
      START WITH mgr        IS NULL
    If you press the schema update button to refresh the display. He mangles connect it by the clause and the view gets marked with a warning/error icon in the diagram of the relationships, but the now decomposed code remains available on reopening of the query designer.

    Same code as above after having clicked on the button of update of schema:
     SELECT Level lev
    , emp.*
       FROM emp
      CONNECT BY
    Other issues are met if the query contains a column CONNECT_BY_ % nickname hierarchical:
    SELECT level
          , emp.*
          , connect_by_root emp.ename root_ename
       FROM emp
      CONNECT BY prior empno = mgr
      START WITH mgr        IS NULL;
    In this case, paste in the code and clicking Update schema button or the OK button translates into a "unexpected Token' error analysis.

    These problems are encountered with the logic model and the relational.

    Is this a known issue? I searched this forum but have not found any references to this.

    Thank you

    Sentinel

    Hi, Sentinel,

    I logged a bug for this.
    You can try 3.3 DM treat it better first problem, analysis of connect_by_root operator will pass if you do not alias.

    Philippe

  • Hierarchical query help need to Oracle

    Hello
    I'm in a deep trouble.

    I want to do a hierarchical query in my TreeView table in oracle. But I want that the query retrieves information path between two nodes.

    Review the table below.

    ------------------------------------------------------
    Node ID | Name of the node. ID of the parent
    -----------------------------------------------------
    1A 0
    2 1
    3C0
    4 2
    -----------------------------------------------------

    What I want is that I'll give you 2 node id in the request. One is the source node and the other is the destination node.
    so if I put 1 node and node 4, I want to be the output

    1-> 2-> 4

    I want just a return line. Or there may be several rows but stands only the node of this path.

    1
    2
    4
    ----

    This means that I don't want to node 3 in the search result.


    More if I have the source as 4 node and the node of destination as 1 then I will also get an output of the query as below-
    4-> 2-> 1

    This means that the search for the query for the result in a way directional bi.


    If anyone can give me some information about who it's going to be great for me.

    Published by: user13276471 on December 31, 2012 03:21

    Hello

    Welcome to the forum!

    Assuming you have 2 separate nodes: Node_A and: node_b, you can find the hierarchy from one to the other like this:

    SELECT     SYS_CONNECT_BY_PATH (node_id, ',')     AS lineage
    FROM     table_x
    WHERE     node_id     IN (:node_a, :node_b)
    AND     LEVEL     > 1
    START WITH     node_id          IN (:node_a, :node_b)
    CONNECT BY     parent_id     = PRIOR node_id
    ;
    

    It will work if: the Node_A is an ancestor of the: node_b, or if: node_b is an ancestor of the: Node_A.
    If is the ancestor of the other, then it will produce 0 rows.

Maybe you are looking for