hierarchical SQL

Hello

I'm looking for help with a hierarchical query.

My table has five columns:

rank (number)
score (number)
name (varchar)
record_id (number)
ParentId (number)

A parentid is a record_id at a higher level in the hierarchy.
Rank and Score are used to control (tri) each level of the hierarchy.

The data looks like this:

grade - score - name - record_id - parentid
----------------------------------------------------------
1 - 1 - name1 - 101-0
1 - 2 - name2 - 102-0
1 - 3 - name3 - 103-0
2 - 1 - name4 - 104-101
2 - 2 - name5 - 105-101
2 - 1 - name6 - 106-102
2 - 2 - Marque7 - 107-102
2 - 1 - name8 - 108-103
2 - 2 - name9 - 109-103

I would like to request to view the data in the following order:

grade - score - name - record_id - parentid
----------------------------------------------------------
1 - 1 - name1 - 101-0
2 - 1 - name4 - 104-101
2 - 2 - name5 - 105-101
1 - 1 - name2 - 102-0
2 - 1 - name6 - 106-102
2 - 2 - Marque7 - 107-102
1 - 1 - name3 - 103-0
2 - 1 - name8 - 108-103
2 - 2 - name9 - 109-103

The simple query to get this sequence of result set is adequate. No need to fill or other characteristics.

Thank you.

All the columns in your sample have same agenda, so it is not possible to tell which column you want to sisters of the order. I'll assume by its name:

select  *
  from  your_table
  start with parentid = 0
  connect by parentid = prior record_id
  order siblings by name
/

For example:

with sample_table as (
                      select 1 grade,1 score,'name1' name,101 record_id,0 parentid from dual union all
                      select 1,2,'name2',102,0 from dual union all
                      select 1,3,'name3',103,0 from dual union all
                      select 2,1,'name4',104,101 from dual union all
                      select 2,2,'name5',105,101 from dual union all
                      select 2,1,'name6',106,102 from dual union all
                      select 2,2,'name7',107,102 from dual union all
                      select 2,1,'name8',108,103 from dual union all
                      select 2,2,'name9',109,103 from dual
                     )
select  *
  from  sample_table
  start with parentid = 0
  connect by parentid = prior record_id
  order siblings by name
/

     GRADE      SCORE NAME   RECORD_ID   PARENTID
---------- ---------- ----- ---------- ----------
         1          1 name1        101          0
         2          1 name4        104        101
         2          2 name5        105        101
         1          2 name2        102          0
         2          1 name6        106        102
         2          2 name7        107        102
         1          3 name3        103          0
         2          1 name8        108        103
         2          2 name9        109        103

9 rows selected.

SQL> 

SY.

Tags: Database

Similar Questions

  • hierarchical sql (part 2) - error: duplicate rows

    Following up on my previous question:

    This hierarchical query has the duplicate in the result set rows:

    Select record_id, parentid, name from my_table
    connect by parentid = prior record_id
    siblings arrested by name;

    Thanks for help.

    ----------

    My table has five columns:

    rank (number)
    score (number)
    name (varchar)
    record_id (number)
    ParentId (number)

    A parentid is a record_id at a higher level in the hierarchy.
    A parentid is a record_id at a higher level in the hierarchy.
    Rank and Score are used to control (tri) each level of the hierarchy.

    The data looks like this:

    grade - score - name - record_id - parentid

    --------------------------------------------------------------------------------
    1 - 1 - name1 - 101-0
    1 - 2 - name2 - 102-0
    1 - 3 - name3 - 103-0
    2 - 1 - name4 - 104-101
    2 - 2 - name5 - 105-101
    2 - 1 - name6 - 106-102
    2 - 2 - Marque7 - 107-102
    2 - 1 - name8 - 108-103
    2 - 2 - name9 - 109-103

    Desired results set:

    grade - score - name - record_id - parentid
    --------------------------------------------------------------------------------
    1 - 1 - name1 - 101-0
    2 - 1 - name4 - 104-101
    2 - 2 - name5 - 105-101
    1 - 1 - name2 - 102-0
    2 - 1 - name6 - 106-102
    2 - 2 - Marque7 - 107-102
    1 - 1 - name3 - 103-0
    2 - 1 - name8 - 108-103
    2 - 2 - name9 - 109-103

    Missing the BEGINNING WITH...?

    SQL> select record_id, parentid, name
      2  from my_table
      3  --Added START WITH
      4  start with parentid = 0
      5  connect by parentid = prior record_id
      6  order siblings by name;
    
     RECORD_ID   PARENTID NAME
    ---------- ---------- ----------
           101          0 name1
           104        101 name4
           105        101 name5
           102          0 name2
           106        102 name6
           107        102 name7
           103          0 name3
           108        103 name8
           109        103 name9
    
    9 rows selected.
    
  • Recursive, HIERARCHICAL query problem

    Hello!

    I have a hierarchical SQL help 'connect' with the result in the following dataset (simplified down point):


    ID       | Parent |   IsData 
    ----------------------------
    A        |        |    N     
      A1     |   A    |    N     
      A2     |   A    |    N     
        X1   |   A2   |    Y     
    B        |        |    N     
      B1     |   B    |    N     
        X2   |   B1   |    Y     
      B2     |   B    |    N     
    C        |        |    N     
      C1     |   C    |    N     
    There are entries of data (X 1 and X 2) and structural (year, Bn, Cn) entries. Some nodes in the tree structure have entries of data like childs, some do not.

    What I need is a third column that says "this node is a node of data below recursively' as indicated below:
     
    
    ID       | Parent |   IsData    |  HasRecursiveDataChilds
    ----------------------------------------------------------
    A        |        |     N       |        Y
      A1     |   A    |     N       |        N
      A2     |   A    |     N       |        Y
        X1   |   A2   |     Y       |        Y/N (doesn't matter)
    B        |        |     N       |        Y
      B1     |   B    |     N       |        Y
        X2   |   B1   |     Y       |        Y/N (doesn't matter)
      B2     |   B    |     N       |        N
    C        |        |     N       |        N
      C1     |   C    |     N       |        N
    I currently do on the client side, after that I got all of the data, which involves an iteration of the full dataset among at least once (if you are familiar with the data). Data is accessible from another (web) application, I want to spend the logic to the server.

    I wonder if this can be done with a simple SQL statement without using the PL/SQL to iterate over the game "manually" of results. I can use all of the features of 10g. Performance is not quite important, so wild sub-sub sub-sub-sub-queries would be ok.

    Thanks for your help,
    Marcus

    OK, this is somewhat a fudge...

    SQL> ed
    Wrote file afiedt.buf
    
      1  with t as (select 'A' as ID, null as parent, 'N' as IsData from dual union all
      2             select 'A1','A','N' from dual union all
      3             select 'A2','A','N' from dual union all
      4             select 'X1','A2','Y' from dual union all
      5             select 'B', null, 'N' from dual union all
      6             select 'B1','B','N' from dual union all
      7             select 'X2','B1','Y' from dual union all
      8             select 'B2','B','N' from dual union all
      9             select 'C',null,'N' from dual union all
     10             select 'C1','C','N' from dual)
     11  -- END OF TEST DATA
     12  select lpad(' ',(level-1)*2,' ')||id as id, parent, isdata
     13        ,NVL((select max(t2.isdata)
     14          from   t t2
     15          connect by parent = prior id
     16          start with parent = t.id),'N') as recursivechilddata
     17  from t
     18  connect by parent = prior id
     19* start with parent is null
    SQL> /
    
    ID         PARENT     ISDATA     RECURSIVECHILDDATA
    ---------- ---------- ---------- -------------------------
    A                     N          Y
      A1       A          N          N
      A2       A          N          Y
        X1     A2         Y          N
    B                     N          Y
      B1       B          N          Y
        X2     B1         Y          N
      B2       B          N          N
    C                     N          N
      C1       C          N          N
    
    10 rows selected.
    
    SQL>
    

    Published by: BluShadow on April 9, 2009 10:59
    removed the redundant code

  • recursion in pl/sql

    Hi all
    I need to know all the nested procedure or the list of functions that are called by a function or a special procedure. I am trying to write a code that I use recursion. I am facing problem to store values in the clause of the SELECT INTO statement because multiple procs may not be stored on a single clue that is to say proclist_v (i). Should I use another type of another object that pl/sql table.please give me an idea

    CREATE or REPLACE PACKAGE finddblink_pack
    IS
    TYPE NameType IS the TABLE OF
    dba_dependencies.referenced_name%type
    INDEX OF DIRECTORY;
    PROCEDURE finddblink_proc (proc_par NameType)
    END finddblink_pack;
    /


    CREATE or REPLACE PACKAGE finddblink_pack BODY
    IS



    PROCEDURE finddblink_proc (proc_par NameType)
    IS
    proclist_v NameType;
    BEGIN
    BECAUSE me in func_par. FIRST... func_par. LAST LOOP
    SELECT referenced_name
    IN proclist_v (i)
    OF dba_dependencies
    WHERE name = upper (func_par (i))
    AND referenced_type ('FUNCTION', 'PROCEDURE', 'BODY of PACKAGE');
    finddblink (proclist_v);
    END LOOP;

    END finddblink_proc;
    END finddblink_pack;

    Well, you don't need recursive plsql for this. Hierarchical SQL will do:

    SQL> CREATE OR REPLACE
      2    PROCEDURE P1
      3      IS
      4      BEGIN
      5          NULL;
      6  END;
      7  /
    
    Procedure created.
    
    SQL> CREATE OR REPLACE
      2    PROCEDURE P2
      3      IS
      4      BEGIN
      5          P1;
      6  END;
      7  /
    
    Procedure created.
    
    SQL> CREATE OR REPLACE
      2    PROCEDURE P3
      3      IS
      4      BEGIN
      5          P2;
      6  END;
      7  /
    
    Procedure created.
    
    SQL> SELECT  referenced_name
      2    FROM  dba_dependencies
      3    START WITH name = 'P3'
      4    CONNECT BY prior referenced_name = name
      5    AND referenced_type in('FUNCTION','PROCEDURE','PACKAGE BODY')
      6  /
    
    REFERENCED_NAME
    ----------------------------------------------------------------
    P2
    P1
    
    SQL> 
    

    SY.

  • By using a WHERE clause in the tree APEX

    Hi all -

    I have a hierarchical SQL query that I display as a tree of the APEX.

    Here is my sample application:

    https://Apex.Oracle.com/pls/Apex/f?p=32581:29

    Login: guest

    PW: app_1000

    workspace: leppard

    I try to add a WHERE clause so that only nodes with the lowest-level children are displayed, i.e. something like "WHERE connect_by_isleaf = 0 OR level = 5'"

    The tree of query with where clause works very well in the SQL command window, but when I add the WHERE clause to my tree apex page no longer displays anything. Is this a problem with APEX or y at - it another way to filter my results?

    Thanks in advance for your suggestions,

    John

    Connect occurs in the first place, the where the provision is applied to these results, effectively cutting in the hierarchical structure. Since the apex has build a hierarchical structure of the query, it relies on the virtual level, which is butchered by applying the where clause. It's a miracle that you're not even receive errors because I expect almost an incorrect json array was built. With no top-level from and only level 5 or end nodes, there is no structure to present: the two apex cannot set a correct representation and not jstree neither. In your request, you will see your "root nodes", but it is not representable.

    I don't know why you want to present it in a tree? Levels both connect_by_is_leaf = 5 will give you everything just a list of nodes without any hierarchical structure.

    The best thing to do is to use a subquery to limit first your dataset and then use it for the basic tree query, this way you violate one of these vital columns.

    For example if you want only nodes and their immediate parent, you can opt for something like this (fast on some testdata model):

    with dataset as (
    select node_id, parent_id
       from treedata
      where connect_by_isleaf = 0
    connect by prior node_id = parent_id
      start with parent_id = 0
    ),
    dataset2 as (
    select node_id, parent_id
      from dataset
    union all
    select node_id, null parent_id
      from treedata
    where node_id in (select parent_id from dataset)
    )
    select level, node_id
       from dataset2
    connect by prior node_id = parent_id
      start with parent_id is null
    
  • A hierarchical report query SQL formatting to display the output as a tree

    4.2.1

    THM:2

    Hello world

    I have a simple request which when I run it should show in a tree like structure as seen in this link

    Hierarchical queries in Oracle SQL

    Any ideas on how I can get this output show upward in an area of report page apex? I tried to put it in a classic report, and it shows just all in one line given the length and spacing. I don't want to use the tree for this.

    Thank you!

    Ryansun-Oracle wrote:

    I have a simple request which when I run it should show in a tree like structure as seen in this link

    Hierarchical queries in Oracle SQL

    Any ideas on how I can get this output show upward in an area of report page apex? I tried to put it in a classic report, and it shows just all in one line given the length and spacing. I don't want to use the tree for this.

    I found that the standard reports and report templates are not really useful in this situation.

    According to exactly how it should be used, you might want to watch a dynamic list using one of the models of hierarchical list, but I tend to use this Tyler Muth & Rob Van Wijk. This can be used in a region in connection with a column named custom report template.

  • How to order a tree balanced with SQL hierarchical queries

    by searching the forum I found this

    Re: Generate tree balanced with SQL hierarchical queries

    is there a way I can order this tree in alphabetical order so that the result looks like

    LEVEL INDENTED_ENAME
    ---------- --------------------
    1 KING BED
    2 BLAKE
    3 ALLEN
    3 JAMES
    MARTIN 3
    3 TURNER
    WARD 3
    2 CLARK
    3 MILLER
    2 JONES
    3 FORD
    4 SMITH
    3 SCOTT
    4 ADAMS

    -the original query-

    SELECT THE LEVEL
    , LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
    FROM scott.emp
    START WITH mgr IS NULL
    CONNECT BY PRIOR empno = mgr
    ;

    LEVEL INDENTED_ENAME
    ---------- --------------------
    1 KING BED
    2 JONES
    3 SCOTT
    4 ADAMS
    3 FORD
    4 SMITH
    2 BLAKE
    3 ALLEN
    WARD 3
    MARTIN 3
    3 TURNER
    3 JAMES
    2 CLARK
    3 MILLER

    Hello

    Bodin wrote:
    Hi Frank, I can order it selectively depending on the level, which means that only siblings stopped at third level, but rest of the brothers and sisters remain Nations United ordered

    It's actually quite difficult. You can "ORDER of brothers and SŒURS BY CASE... ', like this:

    SELECT  LEVEL
    ,      LPAD (' ', 3 * LEVEL) || ename     AS indented_ename
    FROM      scott.emp
    START WITH        mgr     IS NULL
    CONNECT BY         mgr      = PRIOR empno
    ORDER SIBLINGS BY  CASE
                   WHEN  job = 'MANAGER'  THEN  ename
                                              ELSE  NULL
                 END
    ;
    

    In this case to get desired results in table scott.emp, as the lines are LEVEL = 2 if and only if use = "MANAGER".
    But if you reference LEVEL in the CASE expression (for example, if you replace ' job = 'MANAGER' ' with "2 LEVEL =" above "), then you will get the error" ORA-00976: LEVEL, PRIOR or ROWNUM not allowed here. "
    The best way I can think to do exactly what you asked is to do 2 CONNECT BY queries; one just to get the LEVEL and the other for the brothers and SŒURS ORDER BY:
    {code}
    WITH got_lvl AS
    (
    SELECT LEVEL AS lvl
    Bishop
    empno
    ename
    FROM scott.emp
    START WITH mgr IS NULL
    CONNECT BY PRIOR empno = mgr
    )
    SELECT lvl
    , LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
    OF got_lvl
    START WITH mgr IS NULL
    CONNECT BY PRIOR empno = mgr
    BROTHERS AND SŒURS OF ORDER OF CASES
    ONCE lvl = 2 THEN ename
    ANOTHER NULL
    END
    ;
    {code}
    Why you can't simply "Brothers and SŒURS of ORDER BY ename" at all levels? If all you care is the order of the items of LEVEL = 2, then this is probably the most effective and simplest way. It really hurt anything if nodes on levels 3, 4, 5,... are in order, too?

    Here's something you can do if you want to order by different unique things to different levels:
    {code}
    WITH got_sort_key AS
    (
    SELECT LEVEL AS lvl
    , LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
    empno
    SYS_CONNECT_BY_PATH (LPAD (CASE
    WHEN LEVEL = 2
    THEN ename
    Of OTHER TO_CHAR (empno)
    END
    10
    )
    , ','
    ) AS sort_key
    FROM scott.emp
    START WITH mgr IS NULL
    CONNECT BY PRIOR empno = mgr
    )
    SELECT lvl
    indented_ename
    empno
    OF got_sort_key
    ORDER BY sort_key
    ;
    {code}
    However, all possible values of the CASE expression must uniquely identify the node; otherwise, the output won't necessarily hierarchical order. You can assign arbitrary unique IDS to the lines (using the ROW_NUMBER analytic function, for example), but that requires another subquery and is also complex and perhaps as ineffective as the solution above with 2 garages CONNECT.

  • Building the tree balanced with SQL hierarchical queries

    Hi all

    I have the following hierarchical data with different levels of subtree:

    A0
    -A001
    -A00101
    A1
    -A101
    A2
    -A201
    -A20101
    -A201010001

    A0 subtree has 3 levels, A1 subtree has 2 levels and subtree of the A3 is level 4. I want to generate a tree balanced on the data with all levels of the subtree equal to the maximum number of levels available in the whole tree which, in this particular case, is 4.

    I don't know that it is possible with SQL. Script to generate the above mentioned are as below:

    CREATE TABLE codes_tree
    (node_id VARCHAR2 (10))
    parent_node_id VARCHAR2 (10)
    );
    INSERT INTO codes_tree VALUES ('A0', NULL);
    INSERT INTO codes_tree VALUES ('A001', 'A0');
    INSERT INTO codes_tree VALUES ('A00101', 'A001');
    ---
    INSERT INTO codes_tree VALUES ('A1', NULL);
    INSERT INTO codes_tree VALUES ('A101', 'A1');
    ---
    INSERT INTO codes_tree VALUES ('A2', NULL);
    INSERT INTO codes_tree VALUES ('A201', 'A2');
    INSERT INTO codes_tree VALUES ('A20101', 'A201');
    INSERT INTO codes_tree VALUES ('A201010001', 'A20101');

    Any help will be much appreciated.

    Thank you... Best regards

    Published by: naive2Oracle on May 12, 2011 19:40

    Published by: naive2Oracle on May 12, 2011 19:41

    Hello

    Of course, you can do it in SQL.
    One way is to take the normal output of hierarchical and manipulate the result set so that the leaves are repeated as often as necessary to make all branches of the same length. I have Oracle 10.2 available right now, so here's a solution that will work in Oracle 10 (and more):

    WITH     original_hierarchy     AS
    (
         SELECT     node_id
         ,     LEVEL               AS lvl
         ,     CONNECT_BY_ISLEAF     AS isleaf
         ,     ROWNUM               AS rnum
         FROM     codes_tree
         START WITH     parent_node_id     IS NULL
         CONNECT BY     parent_node_id     = PRIOR node_id
    )
    ,     got_max_lvl     AS
    (
         SELECT     o.*
         ,     MAX (lvl) OVER ()     AS max_lvl
         FROM     original_hierarchy     o
    )
    SELECT       LPAD ( ' '
                , 3 * ( ( d.lvl
                     + NVL (c.rnum, 1)
                     - 1
                     )
                   - 1
                   )
                ) || CASE
                   WHEN c.rnum > 1
                   THEN '*' || d.node_id || '*'
                   ELSE        d.node_id
                  END          AS display_id
    FROM            got_max_lvl     d
    LEFT OUTER JOIN       got_max_lvl     c  ON     d.isleaf     = 1
                           AND     c.rnum          <= 1 + d.max_lvl - d.lvl
    ORDER BY  d.rnum
    ,       c.rnum
    ;
    

    With the help of Oracle 11.2, it would be preferable to generate original_hierarchy as above, but to manipulate using a WITH recursive clause.
    Analytical functions often interfere with CONNECT BY, so I used a separate subquery to get max_lvl, do CONNECT BY in a sub-querry and analytic function in a separate subquery. I don't know what is needed on all versions.

    Output of your sample data:

    DISPLAY_ID
    -------------------------------
    A0
       A001
          A00101
             *A00101*
    A1
       A101
          *A101*
             *A101*
    A2
       A201
          A20101
             A201010001
    

    Below is a generic version of the same query, which I used to test this on scott.emp:

    DEFINE     table_name     = scott.emp
    DEFINE     id_col          = empno
    DEFINE     parent_id_col     = mgr
    DEFINE     display_col     = ename
    
    WITH     original_hierarchy     AS
    (
         SELECT     &display_col          AS display_txt
         ,     LEVEL               AS lvl
         ,     CONNECT_BY_ISLEAF     AS isleaf
         ,     ROWNUM               AS rnum
         FROM     &table_name
         START WITH     &parent_id_col     IS NULL
         CONNECT BY     &parent_id_col     = PRIOR &id_col
    )
    ,     got_max_lvl     AS
    (
         SELECT     o.*
         ,     MAX (lvl) OVER ()     AS max_lvl
         FROM     original_hierarchy     o
    )
    SELECT       LPAD ( ' '
                , 3 * ( ( d.lvl
                     + NVL (c.rnum, 1)
                     - 1
                     )
                   - 1
                   )
                ) || CASE
                   WHEN c.rnum > 1
                   THEN '*' || d.display_txt || '*'
                   ELSE        d.display_txt
                  END          AS display_id
    FROM            got_max_lvl     d
    LEFT OUTER JOIN       got_max_lvl     c  ON     d.isleaf     = 1
                           AND     c.rnum          <= 1 + d.max_lvl - d.lvl
    ORDER BY  d.rnum
    ,       c.rnum
    ;
    

    Output:

    DISPLAY_ID
    -----------------------------
    KING
       JONES
          SCOTT
             ADAMS
          FORD
             SMITH
       BLAKE
          ALLEN
             *ALLEN*
          WARD
             *WARD*
          MARTIN
             *MARTIN*
          TURNER
             *TURNER*
          JAMES
             *JAMES*
       CLARK
          MILLER
             *MILLER*
    

    Published by: Frank Kulash, May 13, 2011 06:38
    Adding the generic version

  • SQL SELECT to hierarchical tables: START WITH... CONNECT BY...

    This seems to be a simple problem, but I think that I have enough intelligence SQL to solve.

    I have a table called DE_DOMAIN. The columns of interest are:
    DOMAIN_ID - PK
    NAME
    PARENT_ID - FK (can be NULL), poining to CF of the parent

    What I want is: Returns a hierarchical list, containing: column 3 above as well as the NAME of the parent.

    Regardless of the name of the parent, it works fine:
    SELECT DOMAIN_ID, PARENT_ID, level
    OF DE_DOMAIN
    WHERE SUPERDOMAINE = 2673
    Start by PARENT_ID IS NULL
    Connect DOMAIN_ID PARENT_ID = prior
    BROTHERS AND SŒURS ORDER BY NAME ASC

    and I get:
    11 rec_11 1 Null
    15 rec_15 1 Null
    16 1 Null rec_16
    17 1 Null rec_17
    22 17 2 rec_22
    1 2 17 rec_1
    rec_25 25 17 2
    2 2 17 rec_2

    i.e. records with PK = 1, 22, 25, 2 have all like parent record with PK = 17, then the new column name, they must bear the name of the parent (i.e. rec_17).

    A simple idea?
    Thank you very much.

    Hello

    You can use the FIRST operator in the SELECT clause.
    I don't have a version of your table, so I'll use scott.emp to illustrate:

    SELECT     empno
    ,     ename
    ,     mgr
    ,     PRIOR ename    AS mgr_name
    FROM     scott.emp
    START WITH     mgr     IS NULL
    CONNECT BY     mgr     = PRIOR empno
    ORDER SIBLINGS BY     ename
    ;
    

    Output:

    .    EMPNO ENAME             MGR MGR_NAME
    ---------- ---------- ---------- ----------
          7839 KING
          7698 BLAKE            7839 KING
          7499 ALLEN            7698 BLAKE
          7900 JAMES            7698 BLAKE
          7654 MARTIN           7698 BLAKE
          7844 TURNER           7698 BLAKE
          7521 WARD             7698 BLAKE
          7782 CLARK            7839 KING
          7934 MILLER           7782 CLARK
          7566 JONES            7839 KING
          7902 FORD             7566 JONES
          7369 SMITH            7902 FORD
          7788 SCOTT            7566 JONES
          7876 ADAMS            7788 SCOTT
    
  • Problem (hierarchical data) resolved by using SQL

    Hi I have hierarchical data stored in a table with 3 columns
    Item1, item2, relationship

    relationship column defines if the element1 is parent of item2 or item1 item2 Chile

    I have a fourth column in the same table indicating the entire hierarchy of the family separated by colons;

    example: a1, a2, child then output will be a1:a2.

    I have tried a lot of things to do with a sql but failed and finally did using the recursive function

    Hoping someone can solve the problem in sql

    You will find examples of data to work with as well as the desired result:
    select 'p1' as element1, 'p2' as element2, 'parent' as relationship, 'p1' as output  from dual
    union all
    select 'p2', 'p1', 'child', 'p1:p2' from dual
    union all
    select 'p1', 'p3', 'parent', 'p1' from dual
    union all
    select 'p3', 'p1', 'child', 'p1:p3' from dual
    union all
    select 'p2', 'p4', 'parent', 'p1:p2' from dual
    union all
    select 'p4', 'p2', 'child', 'p1:p2:p4' from dual
    union all
    select 'p2', 'p5', 'parent', 'p1:p2' from dual
    union all
    select 'p5', 'p2', 'child', 'p1:p2:p5' from dual
    union all
    select 'p3', 'p6', 'parent', 'p1:p3' from dual
    union all
    select 'p6', 'p3', 'child', 'p1:p3:p6' from dual
    union all
    select 'p5', 'p7', 'parent', 'p1:p2:p5' from dual
    union all
    select 'p7', 'p5', 'child', 'p1:p2:p5:p7' from dual
    union all
    select 'p5', 'p8', 'parent', 'p1:p2:p5' from dual
    union all
    select 'p8', 'p5', 'child', 'p1:p2:p5:p8' from dual
    union all
    select 'b1', 'b2', 'parent', 'b1' from dual
    union all
    select 'b2', 'b1', 'child', 'b1:b2' from dual
    union all
    select 'b2', 'b3', 'parent', 'b1:b2' from dual
    union all
    select 'b3', 'b2', 'child', 'b1:b2:b3' from dual
    union all
    select 'c1', 'c2', 'parent', 'c1' from dual
    union all
    select 'c2', 'c1', 'child', 'c1:c2' from dual
    union all
    select 'c1', 'c3', 'parent', 'c1' from dual
    union all
    select 'c3', 'c1', 'child', 'c1:c3' from dual
    union all
    select 'c3', 'c5', 'parent', 'c1:c3' from dual
    union all
    select 'c5', 'c3', 'child', 'c1:c3:c5' from dual
    union all
    select 'c3', 'c6', 'parent', 'c1:c3' from dual
    union all
    select 'c6', 'c3', 'child', 'c1:c3:c6' from dual
    union all
    select 'c3', 'c7', 'parent', 'c1:c3' from dual
    union all
    select 'c7', 'c3', 'child', 'c1:c3:c7' from dual
    union all
    select 'a1', null, 'parent', 'a1' from dual
    Kind regards
    Amit

    don't worry, I fixed it...

    with t as(
    select 'p1' as element1, 'p2' as element2, 'parent' as relationship  from dual
    union all
    select 'p2', 'p1', 'child' from dual
    union all
    select 'p1', 'p3', 'parent'from dual
    union all
    select 'p3', 'p1', 'child' from dual
    union all
    select 'p2', 'p4', 'parent' from dual
    union all
    select 'p4', 'p2', 'child' from dual
    union all
    select 'p2', 'p5', 'parent' from dual
    union all
    select 'p5', 'p2', 'child' from dual
    union all
    select 'p3', 'p6', 'parent' from dual
    union all
    select 'p6', 'p3', 'child' from dual
    union all
    select 'p5', 'p7', 'parent' from dual
    union all
    select 'p7', 'p5', 'child' from dual
    union all
    select 'p5', 'p8', 'parent' from dual
    union all
    select 'p8', 'p5', 'child' from dual
    union all
    select 'b1', 'b2', 'parent' from dual
    union all
    select 'b2', 'b1', 'child' from dual
    union all
    select 'b2', 'b3', 'parent' from dual
    union all
    select 'b3', 'b2', 'child' from dual
    union all
    select 'c1', 'c2', 'parent' from dual
    union all
    select 'c2', 'c1', 'child' from dual
    union all
    select 'c1', 'c3', 'parent' from dual
    union all
    select 'c3', 'c1', 'child' from dual
    union all
    select 'c3', 'c5', 'parent' from dual
    union all
    select 'c5', 'c3', 'child' from dual
    union all
    select 'c3', 'c6', 'parent' from dual
    union all
    select 'c6', 'c3', 'child' from dual
    union all
    select 'c3', 'c7', 'parent' from dual
    union all
    select 'c7', 'c3', 'child' from dual
    union all
    select 'a1', null, 'parent' from dual
    ), p as (
    select * from t where relationship='parent')
    ,q as (
    select * from t where relationship='child'
    )
    select element1,element2,relationship,path from (select path,element1,'parent' relationship,element2 from (
    select path,element1,element2,row_number() over (partition by element1,element2 order by length(path) desc) rnum from (
    select ltrim(sys_connect_by_path(element1,':'),':') path,element1,element2 from p connect by prior element2=element1
    )) where rnum=1
    union all
    select path,element1,'child' relationship,element2 from (
    select path,element1,element2,row_number() over (partition by element1,element2 order by length(path) desc) rnum from (
    select ltrim(connect_by_root element2||sys_connect_by_path(element1,':'),':') path,element1,element2 from q connect by prior element1=element2
    )) where rnum=1)
    

    Ravi Kumar

  • How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    WITH cte (col1, col2) AS
    (
    SELECT col1, col2
    FROM dbo. [tb1]
    WHERE col1 = 12
    UNION ALL
    SELECT c.col1, c.col2
    FROM dbo. [tb1] AS c INNER JOIN cte AS p ON c.col2 = p.col1
    )
    DELETE one
    FROM dbo. [tb1] AS an INNER JOIN b cte
    ON a.col1 = b.col1

    Hello
    Something like this maybe:

    DELETE FROM dbo.tb1 a
     WHERE EXISTS (
      SELECT 1
        FROM dbo.tb1 b
      WHERE a.co11 = b.col1
          AND a.col2 = b.col2
       START WITH b.col1 = 12
      CONNECT BY b.col2 = PRIOR b.col1)
    

    Although you need to do here is to check that CONNECT it BY SELECT, returns records you wait first, then the DELETION should work too.

  • SQL Query hierarchical select 2 level parent over sheet.

    Here, we use Oracle 11 g R1. Here is a sample of our Tables of the employee.

    I want you select all managers managers above them (which we call the Site Manager) and direct (that we call the Service Manager)

    Here is the example for the base table.

    SET DEFINE OFF;
    CREATE TABLE EMP_SAMPLE 
    (
      AGENT_ID VARCHAR2(100 BYTE) 
    , FULL_NAME VARCHAR2(100 BYTE) 
    , AGENT_MANAGER VARCHAR2(100 BYTE) 
    ) ;
    
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('JS001','JOHN SMITH',null);
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('AL001','ANN LEE','JS001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('JD001','JOHN DOE','AL001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('MB002','MARY BAKER','AL001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('HM003','HOWARD MONROE','MB002');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('RM001','ROBYN MILLER','MB002');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('DJ002','DAVID JONES','RM001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('WW001','WENDY WONG','MB002');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('PB001','PETER RABBIT','JS001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('BB002','BEN BUNNY','PB001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('TM001','TONY MILLER','BB002');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('PP002','PETER PARKER','RM001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('PP003','PEPPA PIG','PB001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('DB002','daniel baker','HM003');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('TL001','Tom Lee','WW001');
    Insert into EMP_SAMPLE (AGENT_ID,FULL_NAME,AGENT_MANAGER) values ('MS001','Mary Smith',null);
    

    With the example like this data, I would like to that the result looks similar to

    Name of the Manager

    MARY BAKER - Manager of the Site

    HOWARD MONROE - Service Manager

    ROBYN MILLER - Service Manager

    WENDY WOND - Service Manager

    PETER RABBIT Site Manager

    BEN BUNNY - Service Manager

    I guess I should use the hierarchical query to achieve this. I googled to see all the solutions, I tried this under request

    SELECT agent_id, agent_manager, RPAD('.', (level-1)*2, '.') || full_name AS tree,
           level, CONNECT_BY_ROOT agent_id as root_id
           ,CONNECT_BY_ISLEAF AS is_leaf
    
    FROM EMP_SAMPLE
    START WITH agent_manager IS NULL
    CONNECT BY agent_manager = PRIOR agent_id
    ORDER SIBLINGS BY agent_id;
    

    But it seems that the level always starts from the root at the top of the page. I wonder, is it possible to identify even just the level two above the sheet.

    Here is some basic information. We are working on our oracle APEX application. One of the reports can be filtered by the Manager. The list currently shows a little all managers, regardless of what they are 1 senior as general manager, or the first line as a Service Manager Manager. Now, users want to be able to select only Service Manager and Site Manager.

    There is a DB work for updating the table Employee of LDAP. And the LDAP structure is not tidy this (we have some staff members who have no Manager, they are not even CEO). The Administrator told us that it is too busy to store it.

    We have about 20,000 employees in total including 800 East of managers.

    Thanks in advance.

    Ann

    Hi, Ann.

    Ann586341 wrote:

    Here, we use Oracle 11 g R1. Here is a sample of our Tables of the employee.

    I want you select all managers managers above them (which we call the Site Manager) and direct (that we call the Service Manager)

    Here is the example for the base table.

    1. TOGETHER TO DEFINE
    2. CREATE TABLE EMP_SAMPLE
    3. (
    4. AGENT_ID VARCHAR2 (100 BYTE)
    5. FULL_NAME VARCHAR2 (100 BYTE)
    6. AGENT_MANAGER VARCHAR2 (100 BYTE)
    7. ) ;
    8. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('JS001', 'JOHN SMITH', null);
    9. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('AL001', "ANN LEE", "JS001");
    10. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('JD001', 'JOHN DOE', "AL001");
    11. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('MB002', "MARY BAKER", "AL001");
    12. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('HM003', 'HOWARD MONROE', 'MB002');
    13. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('RM001", 'ROBYN MILLER', 'MB002');
    14. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('DJ002', 'DAVID JONES', "RM001");
    15. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('WW001', "WENDY WONG", "MB002");
    16. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('PB001', 'PETER RABBIT', "JS001");
    17. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('BB002', "BEN BUNNY", "PB001");
    18. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('TM001', 'TONY MILLER', "BB002");
    19. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('PP002","PETER PARKER","RM001");
    20. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('PP003', 'PEPPA PIG', "PB001");
    21. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('DB002', "daniel baker", "HM003");
    22. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('TL001', "Tom Lee", "WW001");
    23. Insert into EMP_SAMPLE (AGENT_ID, FULL_NAME, AGENT_MANAGER) values ('MS001', 'Mary Smith', null);

    With the example like this data, I would like to that the result looks similar to

    Name of the Manager

    MARY BAKER - Manager of the Site

    HOWARD MONROE - Service Manager

    ROBYN MILLER - Service Manager

    WENDY WOND - Service Manager

    PETER RABBIT Site Manager

    BEN BUNNY - Service Manager

    I guess I should use the hierarchical query to achieve this. I googled to see all the solutions, I tried this under request

    1. SELECT agent_id, agent_manager, RPAD ('.) (', (level 1) * 2, '.') || full_name LIKE tree,
    2. level, agent_id CONNECT_BY_ROOT as root_id
    3. CONNECT_BY_ISLEAF AS is_leaf
    4. OF EMP_SAMPLE
    5. START WITH agent_manager IS NULL
    6. CONNECT BY PRIOR agent_id = agent_manager
    7. Brothers and SŒURS of ORDER BY agent_id;

    But it seems that the level always starts from the root at the top of the page. I wonder, is it possible to identify even just the level two above the sheet.

    Here is some basic information. We are working on our oracle APEX application. One of the reports can be filtered by the Manager. The list currently shows a little all managers, regardless of what they are 1 senior as general manager, or the first line as a Service Manager Manager. Now, users want to be able to select only Service Manager and Site Manager.

    There is a DB work for updating the table Employee of LDAP. And the LDAP structure is not tidy this (we have some staff members who have no Manager, they are not even CEO). The Administrator told us that it is too busy to store it.

    We have about 20,000 employees in total including 800 East of managers.

    Thanks in advance.

    Ann

    Here's one way:

    WITH leaves LIKE

    (

    SELECT agent_id

    Of emp_sample

    LESS

    SELECT agent_manager

    Of emp_sample

    )

    got_lvl AS

    (

    SELECT-full_name agent_id

    LEVEL AS lvl

    Of emp_sample

    START WITH agent_id IN)

    SELECT agent_id

    Sheets

    )

    CONNECTION BY agent_id = agent_manager PRIOR

    )

    SELECT full_name

    CASE

    WHEN MAX (lvl) = 3

    THEN 'Site Manager'

    ANOTHER "Service Manager"

    END AS title

    OF got_lvl

    GROUP BY full_name-, agent_id

    WITH MIN (lvl) > = 2

    AND MAX (lvl)<=>

    ORDER BY full_name

    ;

    Output:

    FULL_NAME TITLE

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

    BEN BUNNY Service Manager

    MONROE HOWARD Service Manager

    MARY BAKER Site Manager

    PETER RABBIT Site Manager

    ROBYN MILLER Service Manager

    WENDY WONG Service Manager

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

    LEVEL does not always begin with the root; It starts with the lines that meet the condition to START WITH.  If you have a START WITH condition that only roots meet (as in the query you posted) then, Yes, LEVEL will start with the roots.  If you have a condition START WITH answering the criteria only the leaves (as in the query I posted), then LEVEL will start with the leaves.

    I guess just some of your needs.  If seems that a 'Site Manager' is the grandparent of a leaf, but "John Smith" (which is the grandmother of "John Doe", a sheet) is not considered to be a 'Site Manager'.  Similarly, it seems that a 'Service Manager' is the parent (but not the grand-parent) of the leaf, but "Ann Lee" (the mother of "John Doe") is not considered to be a 'Service Manager' for a reason any.

    I guess that full_name is unique.  If full_name is not unique, but agent_id is, then you will need a comment a few line above ends.  (I guess that agent_id is unique and not NULL).

  • Problem with hierarchical query in function PL\SQL

    I have a simple table containing the ID of the parent

    -Create table

    create the table1 table:

    (

    ID NUMBER (12) not null,

    year number 4.

    month NUMBER (2),

    parent_id NUMBER (12)

    );

    -Create/recreate primary, unique and foreign key constraints

    change the table1 table:

    Add primary key constraint PK_TABLE1 (ID);

    change the table1 table:

    Add the foreign key constraint FK_TABLE1_PARENT (PARENT_ID)

    reference TABLE1 (ID);

    data:

    Insert into TABLE1 (id, year, month, parent_id)

    values (5, 2015, 12, 3);

    Insert into TABLE1 (id, year, month, parent_id)

    values (6 (2015), 12, 4);

    Insert into TABLE1 (id, year, month, parent_id)

    values (3 (2015), 11, 1);

    Insert into TABLE1 (id, year, month, parent_id)

    values (4 (2015), 11, 2);

    Insert into TABLE1 (id, year, month, parent_id)

    values (1, 2015, 10, null);

    Insert into TABLE1 (id, year, month, parent_id)

    values (2 (2015), 10, null);

    commit;

    and query

    with h as

    (select t.id, t.year, t.month, CONNECT_BY_ROOT t.id as parent_id from table1 t

    where t.year = 2015 and t.month = 12

    and CONNECT_BY_ROOT t.year = 2015 and CONNECT_BY_ROOT t.month = 10

    connect by prior t.id = t.parent_id)

    Select * from:

    Join table1 t left t.id = h.parent_id;

    It works, but when I put this request in the procedure pl\sql

    create or replace procedure is get_report (p_cur_out on sys_refcursor)

    Start

    Open the p_cur_out for

    with h as

    (select t.id, t.year, t.month, CONNECT_BY_ROOT t.id as parent_id from table1 t

    where t.year = 2015 and t.month = 12

    and CONNECT_BY_ROOT t.year = 2015 and CONNECT_BY_ROOT t.month = 10

    connect by prior t.id = t.parent_id)

    Select * from:

    Join table1 t left t.id = h.parent_id;             

    end get_report;

    /

    They do not compile. And in the fall, with the exception

    Errors of compilation for the PC of the PROCEDURE. GET_REPORT

    [Error: PL/SQL: ORA-00600: internal error code, arguments: [qctcte1], [0], [], [], [], [], [], [], [], [], []]

    Online: 6

    Text: with h as

    Error: PL/SQL: statement ignored

    Online: 6

    Text: with h as

    My version of oracle

    1Oracle Database 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production
    2PL/SQL Release 11.2.0.3.0 - Production
    3CORE Production 11.2.0.3.0
    4AMT for Linux: Version 11.2.0.3.0 - Production
    5NLSRTL Version 11.2.0.3.0 - Production

    What is the problem with my request? Or database? How to solve this problem?

    If you have access to MOS, you can search the reason of it. If you are using left join syntax instead of joining ANSI, owner Oracle procedure compiles and returns the result.

  • Hierarchical Oracle or MS SQL data

    This query to MSSQL

    SELECT  AreaID ,  
            AreaName ,  
            AreaSeq ,  
            ISNULL(( SELECT TOP 1  
                            t1.AreaName  
                     FROM   dbo.Area t1  
                     WHERE  t1.AreaSeq > dbo.Area.AreaSeq  
                     ORDER BY t1.AreaSeq  
                   ), '') AS AppearBeforeArea ,  
            ISNULL(( SELECT TOP 1  
                            t2.AreaSeq  
                     FROM   dbo.Area t2  
                     WHERE  t2.AreaSeq > dbo.Area.AreaSeq  
                     ORDER BY t2.AreaSeq  
                   ), -1) AS AppearBeforeSeq  
    FROM    dbo.Area  
    ORDER BY Area.AreaSeq;  
    

    Gives this result

    sqlseqnoqry.PNG

    In Oracle 12 c


    Create a Table Script:

    create table Area(  
    AreaID Number(5,0),  
    AreaName Varchar2(50 char) ,  
    AreaSeq Number(5,0)  
    );
    

    Insert data:

    Insert Into Area Values(1,'Shastri Nagar', 0);  
    Insert Into Area Values(3,'Saraswati Nagar', 1);  
    Insert Into Area Values(2,'Sardar Pura', 2);  
    Insert Into Area Values(5,'Sojati Gate', 3);  
    Insert Into Area Values(4,'Polo Ground', 4);  
    

    I tried with this hierarchical query but have no idea how to extract columns of rows child/Leaf;

    SELECT    AREAID    , AREANAME    , AREASEQ    
    FROM Area
    START WITH AREASEQ  = 0    
    CONNECT BY PRIOR AREASEQ  < AREASEQ    
    ORDER SIBLINGS BY AREASEQ ;    
    

    I use Oracle 12 c;

    My Question is can I how ResultSet even return with Oracle query without using the service?

    No need for the recursive query... just use an analytic function:

    WITH box (AreaID, AreaName, AreaSeq)

    (SELECT 1, 'Shastri Nagar', 0 double UNION ALL)

    SELECT 3, 'Saraswati Nagar', 1 FROM dual UNION ALL

    SELECT 2, "Sardar Pura", 2 FROM dual UNION ALL

    SELECT 5, "Door of Sojati", 3 FROM dual UNION ALL

    Select the OPTION 4, 'Polo Ground', 4 DOUBLE)

    SELECT areaId, name of the area, AreaSeq

    , lead (areaName) OVER (ORDER BY AreaSeq ASC) AS beforeAreaName

    , lead (areaSeq, 1, -1) OVER (ORDER BY AreaSeq ASC) AS beforeAreaSeq

    area

    /

    HTH

  • START WITH and CONNECT BY in Oracle SQL (hierarchical)

    Hi, the original table as below
    Customer_ID         Account_ID          Paying_Account_ID         Parent_Account_ID          Company_ID
    158                    158                    158                         158                     0
    159                    159                    158                         158                     0
    160                    160                    158                         158                     0
    181                    181                    181                         181                     0
    183                    183                    183                         183                     0
    24669                  24669                  24669                       24669                   0         
    24671                  24671                  24671                       24669                   0
    24670                  24670                  24670                       24669                   0     
    3385127                3385127                3385127                     24670                   0
    To identify the hierarchical relationship of the data, which are PARENT_ACCOUNT_ID & ACCOUNT_ID, here's the query I used.
     select  lpad(' ', 2*level) || A.ACCOUNT_ID AS LEVEL_LABEL, CONNECT_BY_ISCYCLE "Cycle", LEVEL, A.* from ACCOUNT A
    START WITH parent_account_id = account_id
    CONNECT BY NOCYCLE  PRIOR A.ACCOUNT_ID = A.PARENT_ACCOUNT_ID
    AND account_id != parent_account_id
    ;
    It is the result of the query
    Level_Label              Level          Cycle        Customer_ID             Account_ID        Paying_Account_ID      Parent_Account_ID      Company_ID
    158                         1             0              158                     158              158                   158                     0
       159                      2             0              159                     159              158                   158                     0
       160                      2             0              160                     160              158                   158                     0
    181                         1             0              181                     181              181                   181                     0
    183                         1             0              183                     183              183                   183                     0
    24669                       1             0              24669                   24669            24669                 24669                   0       
        24671                   2             0              24671                   24671            24671                 24669                   0
        24670                   2             0              24670                   24670            24670                 24669                   0
            3385127             3             0              3385127                 3385127          3385127               24670                   0
    My question is how can I changed the query to calculate the values for:

    My_Total_PR - number of my accounts to child PR which do not include himself.
    Total_PR - Total number of accounts PR in the overall structure
    My_Total_NPR - number of my accounts of child NPR which do not include himself.
    Total_NPR - Total number of accounts NPR in the overall structure

    * PR stand for responsible for payment, for example the responsible account payment 158 158 (Paying_Account_ID), therefore the Total_PR to 158 is 3 (158, 159, 160)
    * NPR stand responsible for Non-payment, for example the responsible account payment 159 is 158 (Paying_Account_ID), so the Total_NPR for 159 1

    This is the expected result, any advice appreciated. Thank you
    Level_Label                     Level           Cycle           My_Total_PR     Total_PR     My_Total_NPR     Total_NPR     Paying_Account
    158                               1                0                  2              3          0              0              158
        159                           2                0                  0              0          0              1              158
        160                           2                0                  0              0          0              1              158
    181                               1                0                  0              1          0              0              181
    183                               1                0                  0              1          0              0              183
    24669                             1                0                  0              1          3              3              24669                   
        24671                         2                0                  0              1          0              0              24671
        24670                         2                0                  0              1          1              1              24670
            3385127                   3                0                  0              1          0              0              3385127
    Published by: user11432758 on February 14, 2012 01:00

    Published by: user11432758 on February 14, 2012 07:05

    Hello

    user11432758 wrote:
    Hi here is the statement DDL, thank you

    CREATE TABLE "SYSTEM"."ACCOUNT" ...
    

    Do not create your own objects in the diagram of the SYSTEM or any scheme that comes with the database. Create a separate schema and place your items. You'll have fewer security problems, and the migration to a new database will be easier.

    Here's a way to can get the aggregates you want:

    WITH     got_descendants          AS
    (
         SELECT     CONNECT_BY_ROOT account_id     AS ancestor_id
         ,     paying_account_id
         ,     LEVEL                    AS lvl
         FROM     account
         CONNECT BY NOCYCLE     PRIOR account_id     = parent_account_id
              AND          account_id          != parent_account_id
    )
    SELECT       ancestor_id
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id  = paying_account_id THEN 1 END)     AS my_total_pr
    ,       COUNT (CASE WHEN ancestor_id  = paying_account_id THEN 1 END)     AS total_pr
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id != paying_account_id THEN 1 END)     AS my_total_npr
    ,       COUNT (CASE WHEN ancestor_id != paying_account_id THEN 1 END)     AS total_npr
    FROM       got_descendants
    GROUP BY  ancestor_id
    ;
    

    Output:

    `             MY_         MY_
                TOTAL TOTAL TOTAL TOTAL
    ANCESTOR_ID   _PR   _PR  _NPR  _NPR
    ----------- ----- ----- ----- -----
            158     2     3     0     0
            159     0     0     0     1
            160     0     0     0     1
            181     0     1     0     0
            183     0     1     0     0
          24669     0     1     3     3
          24670     0     1     1     1
          24671     0     1     0     0
        3385217     0     1     0     0
    

    This gives the correct numbers, but how can bring us in an order that reflects the hierarchy, with the columns (for example lvl) that come from the hierarchy?
    A solution would be to make two CONNECT BY queries; a service without START WITH clause (like the one above) who collects the aggregates and the other with a START WITH clause (as your original query), which is in the right order and columns such as level_label and level. We could join result sets and get exactly what we want. I'll leave that as an exercise.

    Here is another way, which gets good results with only one CONNECTION PER request:

    WITH     got_descendants          AS
    (
         SELECT     CONNECT_BY_ROOT account_id     AS ancestor_id
         ,     paying_account_id
         ,     account_id
         ,     LEVEL                    AS lvl
         ,     CONNECT_BY_ISCYCLE          AS cycle
         ,     CASE
                  WHEN  CONNECT_BY_ROOT account_id
                      = CONNECT_BY_ROOT parent_account_id
                  THEN  ROWNUM
              END                    AS r_num
         FROM     account
         CONNECT BY NOCYCLE     PRIOR account_id     = parent_account_id
              AND          account_id          != parent_account_id
         ORDER SIBLINGS BY     account_id     -- Optional
    )
    ,     got_o_num     AS
    (
         SELECT     got_descendants.*
         ,     MIN (r_num) OVER (PARTITION BY  account_id)     AS o_num
         ,     MAX (lvl)   OVER (PARTITION BY  account_id)      AS max_lvl
         FROM     got_descendants
    )
    SELECT       LPAD ( ' '
                , 2 * (MIN (max_lvl) - 1)
                )  || ancestor_id                         AS level_label
    ,       MIN (max_lvl)                                AS "Level"
    ,       MIN (cycle)                                   AS "Cycle"
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id  = paying_account_id THEN 1 END)     AS my_total_pr
    ,       COUNT (CASE WHEN ancestor_id  = paying_account_id THEN 1 END)     AS total_pr
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id != paying_account_id THEN 1 END)     AS my_total_npr
    ,       COUNT (CASE WHEN ancestor_id != paying_account_id THEN 1 END)     AS total_npr
    ,       MIN (paying_account_id)                                    AS paying_account
    FROM       got_o_num
    GROUP BY  ancestor_id
    ORDER BY  MIN (o_num)
    ;
    

    Output:

    `                             MY_         MY_
                                TOTAL TOTAL TOTAL TOTAL  PAYING_
    LEVEL_LABEL     Level Cycle   _PR   _PR  _NPR  _NPR  ACCOUNT
    --------------- ----- ----- ----- ----- ----- ----- --------
    158                 1     0     2     3     0     0      158
      159               2     0     0     0     0     1      158
      160               2     0     0     0     0     1      158
    181                 1     0     0     1     0     0      181
    183                 1     0     0     1     0     0      183
    24669               1     0     0     1     3     3    24669
      24670             2     0     0     1     1     1    24670
        3385217         3     0     0     1     0     0  3385217
      24671             2     0     0     1     0     0    24671
    

    That's exactly what you asked for, except that you have posted the line with level_label =' 24671' before the line with level_label = "24671 '. You may not care about who comes first, but if it's important, explains why these lines should be in descending order of account_id, while "159 and 160" are in ascending order. You will need change the ORDERBY brothers and SŒURS clause accordingly.

Maybe you are looking for

  • Why should I now so much time to delete the emails?

    As a user of Thunderbird long term very satisfied for the last two weeks Firefox hangs and takes several seconds to delete even a very short email - why?

  • Why "limit maximum instances of this event in the queue" in the dialog box change events?

    Why I "would limit the maximum instances of this event in the queue" in the dialog box change events? I think that this is new for LV 2014, but I couldn't find an explanation for an instance of good use. A research on OR displays only the 2014 help t

  • Windows Live Movie Maker will play is more story-Board

    Windows Live Movie Maker will play is no longer my storyboard - not even projects that have worked in the past.  Any ideas?  Download the program from Microsoft? I have Vista SP2 ver.6.    Movie maker ver.6.0.6002.18273.

  • Blocked blackBerry combined on a BB 9300 curve smartphones

    I am a complete techno * beep * and managed should not forget the new password I put on my phone and my supplier tells me the only way to substitute the will erase all my info... Is there another way? can I send it BlackBerry? If yes how? Please help

  • Problem with cursor

    I couldn't find the soluction to an error message, have you seen the error before, could you please help me?create or replace procedure update_locationiscur_rec varchar2 (30);cursor up_loc_cur isSelect location_code in the hr_locations_v where addres