Hierachical Query

Hi,
I have one query Master child relation
SELECT D.code DM.CASE
FROM D , DM
WHERE D.PF = '1'
AND D.CODE = DM.PARENT_CODE
ORDER BY 1
I want a output for master code 1 times and multiple recoed from child multiles times
1 10000
20000
2 30000
40000
3 50000
60000
70000
Like these.
Pls help its very urgent
Thanks
Reena

It's not a problem if you'll use Elic's example properely:
SQL> SELECT lag(null, 1, d.dname)
  2  over (partition by e.deptno order by e.ename) as dname,
  3  e.ename
  4  from
  5  emp e, dept d
  6  where e.deptno = d.deptno
  7  ORDER BY D.dname, e.ename
  8  /
DNAME          ENAME
ACCOUNTING     CLARK
               KING
               MILLER
RESEARCH       ADAMS
               FORD
               JONES
               SCOTT
               SMITH
SALES          ALLEN
               BLAKE
               JAMES
               MARTIN
               TURNER
               WARD
14 rows selected.Rgds.

Similar Messages

  • Recursive, hierachical query problem

    Hi!
    I have a hierachical SQL query using "connect by" that result in the following dataset (simplified to get down to the 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 data entries (X1 and X2) and structural (An, Bn, Cn) entries. Some nodes of the structure tree have data entries as childs, some do not.
    What I need is a third column that says "this node has a data node below recursively" as shown 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 this on the client side, after I got all the data, which involves interating through the complete dataset at least once (if you know the data well). Since the data has to be accessed from another (web) app, I want to move the logic to the server.
    I'm wondering if this can be done with a simple SQL statement without using PL/SQL to iterate through the result set "manually". I can use the 10g feature set. Performance is not utterly important, so wild sub-sub-subqueries would be ok.
    Thanks for your help,
    Marcus

    Ok, this is a bit of 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>Edited by: BluShadow on Apr 9, 2009 10:59 AM
    removed redundant code

  • Summing in hierachical query

    Hello
    I'm having real problems trying to put together a hierarchical query. I've not really done too much with them before other than really basic stuff, so any help would be greatly appreciated.
    I'm trying to set up a structure that will let me represent time windows as part of a batch job controller. Each window can have a parent and can also have multiple dependencies...probably best if I use a diagram:
    Main batch
    |
    |----Data Preparation
    |    |
    |    |
    |    |-----60m
    |
    |----Thread 1 *Data preparation
    |    |
    |    |
    |    |-----30m
    |----Thread 2 *Data preparation
    |    |
    |    |
    |    |-----90m
    |----Thread 3 *Data preparation
    |    |
    |    |
    |    |-----180m
    |----Thread 4 *Data preparation
    |    |
    |    |
    |    |-----10m
    |
    |----Reports *Thread 1,2,3,4
    |    |
    |    |
    |    |-----130m
    |
    |-----11 hoursThis shows that the "Main Batch" window is 11 hours in total. It contains 6 further windows each with their own durations. Each window can also be dependent on the completion of one or more other windows. So in this case, the "Reports" window is owned by the "Main Batch" window, but is dependent on the completion of Threads 1-4. The text in itallics denotes a dependency. Represented another way:
                Main batch(11hr)
                      |
               data preparation(1hr)
                      |
        |         |        |         |
    thread 1  thread 2 thread 3  thread 4
      (30m)    (1hr30m)  (3hr)     (10m)
        |         |        |         |
                      |
                 Report(2hr10m)To represent this I've got 2 tables and data like so:
    CREATE TABLE dt_test_window
    (   id                  NUMBER,
        label               VARCHAR2(30),
        duration            INTERVAL DAY TO SECOND,
        parent_id           NUMBER
    CREATE TABLE dt_test_window_dependency
    (   dependent_id        NUMBER,
        dependee_id         NUMBER
    INSERT
    INTO
        dt_test_window
    VALUES
        (   1,
            'Main batch window',
            TO_DSINTERVAL('0 11:00:00'),
            NULL
    INSERT
    INTO
        dt_test_window
    VALUES
        (   2,
            'Data preparation',
            TO_DSINTERVAL('0 01:00:00'),
            1
    INSERT
    INTO
        dt_test_window
    VALUES
        (   3,
            'Thread 1',
            TO_DSINTERVAL('0 00:30:00'),
            1
    INSERT
    INTO
        dt_test_window
    VALUES
        (   4,
            'Thread 2',
            TO_DSINTERVAL('0 01:30:00'),
            1
    INSERT
    INTO
        dt_test_window
    VALUES
        (   5,
            'Thread 3',
            TO_DSINTERVAL('0 03:00:00'),
            1
    INSERT
    INTO
        dt_test_window
    VALUES
        (   6,
            'Thread 4',
            TO_DSINTERVAL('0 00:10:00'),
            1
    INSERT
    INTO
        dt_test_window
    VALUES
        (   7,
            'Thread 0 Reports',
            TO_DSINTERVAL('0 02:10:00'),
            1
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   3,
            2
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   4,
            2
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   5,
            2
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   6,
            2
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   7,
            3
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   7,
            4
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   7,
            5
    INSERT
    INTO
        dt_test_window_dependency
    VALUES
        (   7,
            6
    /What I'd like to do is run a query that will show the duration of each window, and also sum up the intervals for each window that it depends on, and where there are multiple dependencies at the same level, pick the longest duration. This would allow me to put in a start time, and show the expected end time for each stage. For these data I would expect to see
    start_time  := 12:00
    label               duration    max_end_time
    Main batch          11:00:00    23:00
    Data preparation    01:00:00    13:00
    Thread 1            00:30:00    13:30
    Thread 2            01:30:00    14:30
    Thread 3            03:00:00    16:00
    Thread 4            00:10:00    13:10
    Reports             02:10:00    18:10The exected time for the reports to finish would be 18:10 because they depend on threads 1-4. Thread 3 is the longest running so it cannot start until 16:00.
    This is the query I have and the result I get, can anyone tell me where I'm going wrong?
    tylerd@DEV2> WITH batch AS
      2  (   SELECT
      3          TO_DATE('23-JAN-2007 12:00:00','DD-MON-YYYY HH24:MI:SS') start_date
      4      FROM
      5          dual
      6  )
      7  SELECT
      8      id,
      9      label,
    10      parent_id,
    11      batch.start_date + max_duration
    12  FROM
    13      (   SELECT
    14              win.id,
    15              win.label,
    16              win.parent_id,
    17              MAX(    (   SELECT
    18                          SUM_INTERVAL(win_parent.duration)
    19                      FROM
    20                          dt_test_window win_parent
    21                      WHERE
    22                          win_parent.id = win_dep.dependee_id
    23                      CONNECT BY
    24                          PRIOR dependee_id = dependent_id
    25                      ) + win.duration
    26                 ) max_duration
    27          FROM
    28              dt_test_window win,
    29              dt_test_window_dependency win_dep
    30          WHERE
    31              win.id = win_dep.dependent_id(+)
    32          GROUP BY
    33              win.id,
    34              win.label,
    35              win.parent_id
    36      ),
    37      batch
    38  ORDER BY
    39      id
    40  /
            ID LABEL                           PARENT_ID BATCH.START_DATE+MA
             1 Main batch window                         23/01/2007 23:00:00
             2 Data preparation                        1 23/01/2007 13:00:00
             3 Thread 1                                1 23/01/2007 13:30:00
             4 Thread 2                                1 23/01/2007 14:30:00
             5 Thread 3                                1 23/01/2007 16:00:00
             6 Thread 4                                1 23/01/2007 13:10:00
    7 Thread 0 Reports 1 23/01/2007 17:10:00<-should be 18:10
    7 rows selected.Thank you
    David
    p.s.
    Here's the code for sum_interval:
    CREATE OR REPLACE TYPE SumInterval AS OBJECT
    (     runningSum INTERVAL DAY(9) TO SECOND(9),
              Responsible for initialising the aggregation context
         STATIC FUNCTION ODCIAggregateInitialize
         (      actx IN OUT SumInterval
         ) RETURN NUMBER,
              Adds values to the aggregation context - NULLS are ignored
         MEMBER FUNCTION ODCIAggregateIterate
         (      self  IN OUT SumInterval,
              val   IN       DSINTERVAL_UNCONSTRAINED
         ) RETURN NUMBER,
              Routine invoked by Oracle to combine two aggregation contexts.  This happens when an
              aggregate is invoked in parallel
         MEMBER FUNCTION ODCIAggregateMerge
         (     self  IN OUT SumInterval,
              ctx2 IN      SumInterval
         ) RETURN NUMBER,
              Terminate the aggregation context and return the result
         MEMBER FUNCTION ODCIAggregateTerminate
         (     self             IN   SumInterval,
              returnValue  OUT DSINTERVAL_UNCONSTRAINED,
              flags           IN   NUMBER
         ) RETURN NUMBER
    CREATE OR REPLACE TYPE BODY SumInterval AS
         STATIC FUNCTION ODCIAggregateInitialize
         (      actx IN OUT SumInterval
         )      RETURN NUMBER
         IS
         BEGIN
              IF actx IS NULL THEN
                   actx := SumInterval (INTERVAL '0 0:0:0.0' DAY TO SECOND);
              ELSE
                   actx.runningSum      := INTERVAL '0 0:0:0.0' DAY TO SECOND;
              END IF;
              RETURN ODCIConst.Success;
         END;
         MEMBER FUNCTION ODCIAggregateIterate
         (      self  IN OUT SumInterval,
              val   IN     DSINTERVAL_UNCONSTRAINED
         ) RETURN NUMBER
         IS
         BEGIN
              self.runningSum      := self.runningSum + val;
              RETURN ODCIConst.Success;
         END;
         MEMBER FUNCTION ODCIAggregateTerminate
         (      self        IN  SumInterval,
              ReturnValue OUT DSINTERVAL_UNCONSTRAINED,
              flags       IN  NUMBER
         ) RETURN NUMBER
         IS
         BEGIN
              returnValue := self.runningSum;
              RETURN ODCIConst.Success;
         END;
         MEMBER FUNCTION ODCIAggregateMerge
         (     self IN OUT SumInterval,
              ctx2 IN     SumInterval
         ) RETURN NUMBER
         IS
         BEGIN
              self.runningSum      := self.runningSum + ctx2.runningSum;
              RETURN ODCIConst.Success;
         END;
    END;
    CREATE OR REPLACE FUNCTION sum_interval
    (      x DSINTERVAL_UNCONSTRAINED
    ) RETURN DSINTERVAL_UNCONSTRAINED
    PARALLEL_ENABLE
    AGGREGATE USING SumInterval;
    /     

    Hello
    After some more experimentation I've found that I need to decode the dependent/dependee ids and group on that to get the correct result. Using id 7(Reports) as the starting point
    tylerd@DEV2> SELECT
      2      win_lookup.parent_id,
      3      win_lookup.id,
      4      win_dep_lookup.dependent_id,
      5      win_dep_lookup.dependee_id,
      6      win_lookup.duration,
      7      CONNECT_BY_ISLEAF
      8  FROM
      9      dt_test_window_dependency win_dep_lookup,
    10      dt_test_window win_lookup
    11  WHERE
    12      win_lookup.id = win_dep_lookup.dependee_id
    13  START WITH
    14      win_dep_lookup.dependent_id=7
    15  CONNECT BY
    16      PRIOR win_dep_lookup.dependee_id = win_dep_lookup.dependent_id
    17  /
    PARENT_ID         ID DEPENDENT_ID DEPENDEE_ID DURATION                       CONNECT_BY_ISLEAF
             1          3            7           3 +00 00:30:00.000000                            0
             1          2            3           2 +00 01:00:00.000000                            1
             1          4            7           4 +00 01:30:00.000000                            0
             1          2            4           2 +00 01:00:00.000000                            1
             1          5            7           5 +00 03:00:00.000000                            0
             1          2            5           2 +00 01:00:00.000000                            1
             1          6            7           6 +00 00:10:00.000000                            0
             1          2            6           2 +00 01:00:00.000000                            1
    8 rows selected.I can see that if I group using decode and CONNECT_BY_ISLEAF like so:
    tylerd@DEV2> SELECT
      2      DECODE(CONNECT_BY_ISLEAF, 0, win_dep_lookup.dependee_id,win_dep_lookup.dependent_id) grouping_id,
      3      SUM_INTERVAL(win_lookup.duration)
      4  FROM
      5      dt_test_window_dependency win_dep_lookup,
      6      dt_test_window win_lookup
      7  WHERE
      8      win_lookup.id = win_dep_lookup.dependee_id
      9  START WITH
    10      win_dep_lookup.dependent_id=7
    11  CONNECT BY
    12      PRIOR win_dep_lookup.dependee_id = win_dep_lookup.dependent_id
    13  GROUP BY
    14      DECODE(CONNECT_BY_ISLEAF, 0, win_dep_lookup.dependee_id,win_dep_lookup.dependent_id)
    15  /
    GROUPING_ID SUM_INTERVAL(WIN_LOOKUP.DURATION)
              3 +000000000 01:30:00.000000000
              4 +000000000 02:30:00.000000000
              5 +000000000 04:00:00.000000000
              6 +000000000 01:10:00.000000000I get the correct result for each thread. The problem is, when I try to plug this into the main query to select the MAX of these dependencies, I get
    tylerd@DEV2> WITH batch AS
      2  (   SELECT
      3          TO_DATE('23-JAN-2007 12:00:00','DD-MON-YYYY HH24:MI:SS') start_date
      4      FROM
      5          dual
      6  )
      7  SELECT
      8      id,
      9      label,
    10      parent_id,
    11      batch.start_date + max_duration
    12  FROM
    13      (   SELECT
    14              win.id,
    15              win.label,
    16              win.parent_id,
    17              MAX(    (   SELECT
    18                              SUM_INTERVAL(win_lookup.duration)
    19                          FROM
    20                              dt_test_window_dependency win_dep_lookup,
    21                              dt_test_window win_lookup
    22                          WHERE
    23                              win_lookup.id = win_dep_lookup.dependee_id
    24                          START WITH
    25                              win_dep_lookup.dependent_id=win.id
    26                          CONNECT BY
    27                              PRIOR win_dep_lookup.dependee_id = win_dep_lookup.dependent_id
    28                          GROUP BY
    29                              DECODE(CONNECT_BY_ISLEAF, 0, win_dep_lookup.dependee_id,win_dep_lookup.dependent_id)
    30                      ) + win.duration
    31                 ) max_duration
    32          FROM
    33              dt_test_window win,
    34              dt_test_window_dependency win_dep
    35          WHERE
    36              win.id = win_dep.dependent_id(+)
    37          GROUP BY
    38              win.id,
    39              win.label,
    40              win.parent_id
    41      ),
    42      batch
    43  ORDER BY
    44      id
    45  /
                MAX(    (   SELECT
    ERROR at line 17:
    ORA-01427: single-row subquery returns more than one rowWhich I do understand, I just don't know how to get round it.
    Any ideas?
    David

  • Complex Hierachical query

    Hi
    I have some columns, I put 4 columns that I want build a Hierachal tree
    CD_TP_Strut
    CD_Strut
    CD_TP_Strut_Parent
    CD_Strut_Parent
    How can I to use Connect by ?
    Examples data of my table
    I have some columns, I put 4 columns that I want build a Hierachal  tree
    CD_TP_Strut
    CD_Strut
    CD_TP_Strut_Parent
    CD_Strut_Parent
    ExamplesCD_TP_Strut CD_Strut CD_TP_Strut_Parent CD_Strut_Parent
    0 1 NULL NULL
    1 1 0 1
    2 1 1 1
    3 1 2 1
    4 1 3 26
    5 1 4 16
    Message was edited by:
    muttleychess
    Message was edited by:
    muttleychess

    I still think that you labeled the columns
    incorrectly in your example data, but here goes:
    START WITH CD_TP_Strut_Parent is null
    AND CD_Strut_Parent is null
    CONNECT BY prior CD_TP_Strut = CD_TP_Strut_Parent
    AND prior CD_Strut = CD_Strut_ParentReally , Edited labels column

  • Issue in Hierachichal Query

    HI All,
    I am having a issue related to the hierachal query execution in oracle 10g versions. Could any one help me with this issue?
    1) When executes the following query I can observe a result set like this *(ORACLE instance is -10.2.0.4)*
    70, 70-->71 ,70->71->72, 70->71->72->73, 72, 72->73
    SELECT *
    FROM
    SELECT dp.contract contract,
    CONNECT_BY_ROOT dp.catalog_no root_catalog_no,
    sys_connect_by_path(dp.catalog_no, '^') part_path,
    dp.catalog_no catalog_no,
    dp.valid_from valid_from,
    dp.valid_to valid_to
    FROM c_distribution_part_tab dp
    START WITH dp.replaced_part_no IS NULL
    CONNECT BY PRIOR dp.catalog_no = dp.replaced_part_no
    AND PRIOR dp.contract = dp.contract
    AND PRIOR dp.valid_from >= dp.valid_from
    AND PRIOR dp.valid_to <= dp.valid_to
    WHERE root_catalog_no LIKE '7_'
    ORDER BY part_path,
    valid_from,
    valid_to;
    2) But when this same query executes in the ORACLE 10.2.0.3 one line is missing in the result set (70->71->72->73, is missing)
    70, 70->71,70->71->72, 72,72->73
    3) BUT if I create a copy in that db version 10.2.0.3 from the same table (CREATE TABLE c_distribution_part_tab_copy AS SELECT * FROM c_distribution_part_tab; ) and executing the above query replacing the c_distribution_part_tab with c_distribution_part_tab_copy I am getting the result set correct.With out no issue.
    4) Also if I change the where condition from
    AND PRIOR dp.valid_from >= dp.valid_from
    AND PRIOR dp.valid_to <= dp.valid_to
    to
    AND PRIOR dp.valid_from = dp.valid_from
    AND PRIOR dp.valid_to = dp.valid_to
    I am getting the correct result set event with the original table c_distribution_part_tab.
    5) DATA set is identical in both ORACLE versions.
    6) DATA set
    contract catalog_no replaced_part-no valid_from valid_to
    1 70 null 2011-1-1 2011-12-31
    1 71 70 2011-1-1 2011-12-31
    1 72 71 2011-1-1 2011-12-31
    1 72 null 2010-1-1 2010-12-31
    1 73 72 2010-1-1 2010-12-31
    1 73 72 2011-1-1 2011-12-31
    Thanks in advance if can give me any idea.
    Thilini
    Edited by: 845728 on Mar 19, 2011 8:34 AM
    Edited by: 845728 on Mar 19, 2011 8:36 AM

    Working for me on 10.2.0.3
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    SQL>   SELECT *
      2      FROM (    SELECT dp.contract contract
      3                      ,CONNECT_BY_ROOT dp.catalog_no root_catalog_no
      4                      ,SYS_CONNECT_BY_PATH (dp.catalog_no, '^') part_path
      5                      ,dp.catalog_no catalog_no
      6                      ,dp.valid_from valid_from
      7                      ,dp.valid_to valid_to
      8                  FROM c_distribution_part_tab dp
      9            START WITH dp.replaced_part_no IS NULL
    10            CONNECT BY     PRIOR dp.catalog_no = dp.replaced_part_no
    11                       AND PRIOR dp.contract = dp.contract
    12                       AND PRIOR dp.valid_from >= dp.valid_from
    13                       AND PRIOR dp.valid_to <= dp.valid_to)
    14     WHERE root_catalog_no LIKE '7%'
    15  ORDER BY part_path, valid_from, valid_to;
      CONTRACT ROOT_CATALOG_NO PART_PATH                                                                           
             1              70 ^70                                                                                 
             1              70 ^70^71                                                                              
             1              70 ^70^71^72                                                                           
             1              70 ^70^71^72^73                                                                        
             1              72 ^72                                                                                 
             1              72 ^72^73                                                                              
    6 rows selected.
    SQL> G.

  • Query for finding shortest path

    I know nothing about Oracle Spatial. Just want to know if this query is possible using Spatial.
    Given the following data for undirected weighted graph,
    v1: vertex 1
    v2: vertex 2
    w: weight between vertices v1 and v2(or, distance of edge)
    table name : wgraph
    v1  v2  w
    k   a    2
    m  a    3
    k   c    1
    k   d    4
    c   b    2
    h   d    3
    c   h    3
    h   e    4
    e   b    4
    m  b    6Can I make a query which gives the shortest path from vertex 'a' to vertext 'e' using Spatial?
    If this possible, that query gives the following result. (row-spanning form)
    I think this is almost impossible using just a hierachical query.
    Any method for this in Oracle Spatial?
    spath
    a
    k
    c
    b
    e
    This is not a sort of homework or exam, just my interest.
    Thx in advance.
    Query Your Dream & Future at
    http://www.soqool.com

    yes why not! in your case just create a logical network- called LRS Network and insert your vertices in node- table and additional information plus cost in the link table.
    you can find ways using by dijkstra and A*

  • Reg. Reccursive Query

    Hi,
    My requirement is that I have a condition which gets 2 values as the input of a search query, I need to search the same from a table.
    Eg. consider a table(Employee) with 5 columns say Emp.ID,Name,Salary,DOJ and role.
    I will be getting Emp.ID(mandatory field) and Name(optional field) as input of the search criteria.
    Based on the Emp.Id entered I need to perform a reccursive query which will traverse to the top on the basis of Role(Seniority).
    Suppose if Emp.ID of a Clerk is entered then it performs reccursive query and goes till the senior most level (ie) Chairman and gives out the Emp.ID of the Chairman.
    kindly help me in writing a suitable query for this...
    hope you have understood my requirement?
    Regards,
    Symonds

    I'm not sure to understand as well, but maybe do you mean hierachical query ?
    Nicolas.

  • Hierarchical query: how to find out the root node

    Hi to all.
    I have a table with the following values:
    user manager
    Tom
    John
    Peter Tom
    Steven Peter
    Sean Peter
    Jim John
    Bill John
    Ken Bill
    So my hierachical query is as follow:
    SELECT rpad(' ',(level-1)*3)||user as user_root, managerFROM My_Table
    START WITH manager IS NULL
    CONNECT BY manager = PRIOR user
    ORDER SYBLINGS BY user
    user_root manager
    Tom
    Peter Tom
    Steven Peter
    Sean Peter
    John
    Jim John
    Bill John
    Ken Bill
    But I want also to know the top manager of each user. I want my output to be as follows:
    user_root manager top_manager
    Tom
    Peter Tom Tom
    Steven Peter Tom
    Sean Peter Tom
    John
    Jim John John
    Bill John John
    Ken Bill Ken
    Any hlp will be appreciated. Thanks a lot.
    Regards, Beroetz

    In 9i sys_connect_by_path can help:
    SQL> select empno, ename, mgr
      2  from emp
      3  start with mgr is null
      4  connect by prior empno = mgr
      5  /
         EMPNO ENAME             MGR
          7698 BLAKE
          7499 ALLEN            7698
          7521 WARD             7698
          7654 MARTIN           7698
          7844 TURNER           7698
          7900 JAMES            7698
          7839 KING
          7566 JONES            7839
          7788 SCOTT            7566
          7876 ADAMS            7788
          7902 FORD             7566
          7369 SMITH            7902
          7782 CLARK            7839
          7934 MILLER           7782
    14 rows selected.
    SQL> select ename, mgr,
      2  substr(sys_connect_by_path(ename,'/'),
      3  2,instr(sys_connect_by_path(ename,'/'),'/',2)-2) top
      4  from emp
      5  start with mgr is null
      6  connect by prior empno = mgr
      7  /
    ENAME             MGR TOP
    BLAKE
    ALLEN            7698 BLAKE
    WARD             7698 BLAKE
    MARTIN           7698 BLAKE
    TURNER           7698 BLAKE
    JAMES            7698 BLAKE
    KING
    JONES            7839 KING
    SCOTT            7566 KING
    ADAMS            7788 KING
    FORD             7566 KING
    SMITH            7902 KING
    CLARK            7839 KING
    MILLER           7782 KING
    14 rows selected.Rgds.

  • Tutorial on ADF Faces/Toplink

    I'm in the process of evaluating JDev 10.1.3, with particular focus on ADF Faces. I'm not seeing some simple examples that combine the use of ADF Faces and Toplink, and my ignorant attempts to combine the two have resulted only in frustration. Has anybody posted something along those lines out there, or am I just blind?

    Thanks for the link i already read abour but i didn't find any code sample or tutorials for "query by example" and "hierachical query".
    These functionalities are great enhancement for entity bean projects that doesn't offer a way to solve such need easily, isn't.
    Something exists about this in the docs i didn't seen ?
    Here is the select connect by i want to reproduce
    select      level
         , substr( SYS_CONNECT_BY_PATH( parentlabel.label, '/' ) ,0,50 ) "Path"
         , flexitemparent_i
         , flexitemchild_i
         , substr( parentlabel.label, 0, 50 ) "parent.label"
         , substr( childlabel.label, 0, 50 ) "child.label"
    from      flextree
         , flextreenode
         , flexitem parent
         , flextext parentlabel
         , flexitem child
         , flextext childlabel
    where     flextree.flextree_i = 1
    and     flextree.flextree_i = flextreenode.flextree_i
    and     flextreenode.flexitemparent_i = parent.flexitem_i
    and     parent.flexitem_i = parentlabel.flexitem_i
    and     parentlabel.locale = ( select value from sys.v_$nls_parameters where parameter= 'NLS_LANGUAGE' )
    and     flextreenode.flexitemchild_i = child.flexitem_i
    and     child.flexitem_i = childlabel.flexitem_i
    and     childlabel.locale = ( select value from sys.v_$nls_parameters where parameter= 'NLS_LANGUAGE' )
    connect by prior flexitemchild_i = flexitemparent_i
    start with flextree.flexitem_i = flextreenode.flexitemparent_i
    order siblings by childlabel.label
    /

  • Alternative for Hierarchical Queries

    Hi all,
    Is there any other way to implement the Hierachical Query in Oracle. Let us assume the following example of the Scott.emp Table. The output of the table must be in a Hierarchical manner as follows :
    ORG_CHART EMPNO MGR JOB
    KING 7839 PRESIDENT
    JONES 7566 7839 MANAGER
    SCOTT 7788 7566 ANALYST
    ADAMS 7876 7788 CLERK
    FORD 7902 7566 ANALYST
    SMITH 7369 7902 CLERK
    BLAKE 7698 7839 MANAGER
    ALLEN 7499 7698 SALESMAN
    WARD 7521 7698 SALESMAN
    MARTIN 7654 7698 SALESMAN
    TURNER 7844 7698 SALESMAN
    JAMES 7900 7698 CLERK
    CLARK 7782 7839 MANAGER
    MILLER 7934 7782 CLERK
    The above structure can be achieved using the following implementation by using the clauses namely CONNECT BY PRIOR, LEVEL and START WITH :
    SELECT LPAD(' ',2*(LEVEL-1)) || ename org_chart,
    empno, mgr, job
    FROM emp
    START WITH job = 'PRESIDENT'
    CONNECT BY PRIOR empno = mgr;
    The above query works fine without any issues.
    But is there any other way to implement the above logic without using the above hierarchical query clauses.
    Please help me on the above.
    Thanks in advance.
    Regards
    Raj

    Thanks.
    Why I require this implementation is we have an software which runs both on Oracle and SQL Server, we accomplish the same very easily in Oracle by using the Hierarchical Queries already available in Oracle. But there is no such predefined keywords to implement in SQL server. That is the purpose of the above.
    When we can achieve the same in a alternative way in Oracle, the same I feel can be implemented in SQL server.
    Raj
    Not without dropping into PLSQL, but this is not easy, and why bother, if your query works OK?

  • Crystal Report based on BEX 3.X query + Hierachies

    Hi,
    I have built a Crystal Report (2008) based on BW Bex 3.5 query.
    The report has a hierachical group based on a hierachy
    similar to the strategy used in
    http://blog.mastering-sap-and-businessobjects.com/2009/07/10/crystal-reports-and-sap-bw-hierarchies--conditional-formatting-part-2.aspx
    Certain sub and parent nodes in the hierachy have suppressed to make sure the report is formatted correctly.
    The user running the report does NOT have the option of choosing the level of nodes to hide  or show.
    At this point in time the report is showing the correct nodes, however there is a concern that once users start re-arranging the hierchies and adding nodes that the reports will have to be maintained. (Which I think is a catch 22 situation)
    Does anyone have another suggestion how to have the reports be "Dynamic" (based on the hierachy) and still not have the danger of the hierachies changing and affecting the Reports
    (I certainly can think of no other ways EXCEPT creating a structure in the BW Query - which means that in any case if the hierachies changes, the BW Query will have to be maintained)
    Kind Regards,
    Nicole

    Hi,
    Crystal Reports is using a parent child relationship which means the complete hierarchy is dynamic and in case your hierarchy is changing on the BW side Crystal Reports will pick up those changes automatically - assuming we talking about additional levels or levels been removed.
    ingo

  • Query Hierachies with MDX

    Hi colleagues,
    currently I´m trying to execute MDX-Statements with a tool called TurboQueryLight.
    I want to extract specific Hierachies out of the SAP BW and tried following Statements so far:
    SELECT .MEMBERS ON COLUMNS,[PPROCTNTN].MEMBERS ON ROWS FROM SAP VARIABLES INCLUDING .[FDA44FDDE546E74C9217783AFB06AA5B]
    SELECT .MEMBERS ON COLUMNS,[PPROCTNTN].MEMBERS ON ROWS FROM SAP VARIABLES INCLUDING .[CRM_40_KEYCAPS]
    With both Statements I get ab Error like:
    OLAP Data adapter error: Invalid MDX command with FDA44FDDE546E74C9217783AFB06AA5B (or CRM_40_KEYCAPS)
    Any idea how to initialize the SAP VARIABLES coorectly to get a specific hierachie?
    Your help in this will be much appreciated
    Regards
    S.Löffler

    Now I created a new statement with a little help from the MDX Testeditor which looks like this:
    SELECT .MEMBERS ON AXIS(0),NON EMPTY .[LEVEL01].MEMBERS ON AXIS(1) FROM SAP VARIABLES INCLUDING
    Executing this query takes some time and ends with an OLAP Data adapter error: tY8 .
    Any suggestions what´s going wrong now?

  • Complex Query (Maybe hierachical)

    I have 2 tables with following field
    Table A
    - ID1
    - Parent ID
    Table B
    - Parent ID (from table 1)
    - Name
    For table A each Parent ID can have a number of child ID1's. Furthermore I have another table which gives me a name for the Parent ID.
    I need a query which will return the results in the following format:
    Each record returned will have one Parent ID, followed by the Name of the parent (which comes from table B) followed by one or more ID1 (which belong to that Parent ID), the IDs must be comma separated.
    I think I need a hierarchical query, maybe something like sys_connect_by_path is needed to give me the comma separated part, a template query for the mentioned scenario would be much appreciated.

    Or sth like
    SQL>  with t1 as (
    select empno id1, mgr parent_id from emp)
    ,t2 as
    select empno parent_id, ename name from emp
    select t1.parent_id,
           ltrim(max(sys_connect_by_path(name,',')) keep (dense_rank last order by length(sys_connect_by_path(name,','))),',') names
      from t1,t2
    where t1.parent_id=t2.parent_id
    connect by prior id1 = t1.parent_id
    group by t1.parent_id
    PARENT_ID NAMES                                  
          7566 KING,JONES                             
          7698 KING,BLAKE                             
          7782 KING,CLARK                             
          7788 KING,JONES,SCOTT                       
          7839 KING                                   
          7902 KING,JONES,FORD                        
    6 rows selected.

  • Problem with different execution paths in hierarchical query

    Hello,
    I have problems with the following query:
    SELECT DISTINCT P.ID FROM PRODUCTELEMENTIMPL P WHERE ( ( LABEL = 'SomeLabel' AND PRODUCTELEMENTTYPE = 'SomeText' AND ( STATE = 'created' OR STATE = 'stored' OR STATE = 'archived' OR STATE = 'archivedRestored' ) ) ) START WITH P.ID = 42 CONNECT BY PRIOR P.ID = P.PARENT
    We have two databases (an Oracle 10g XE and Oracle10g Enterprise). In the XE Database the query is executed very fast, but in the main installation it takes minutes. If I "explain" the query I get two different execution paths:
    The fast:
    ID      PARENT_ID      LEVEL      SQL      Kosten      Anzahl Zeilen
    0      -      1      SELECT STATEMENT      20      49
    1      0      2      HASH UNIQUE      20      49
    2      1      3      FILTER      -      -
    3      2      4      CONNECT BY WITH FILTERING      -      -
    4      3      5      TABLE ACCESS BY INDEX ROWID PRODUCTELEMENTIMPL (TABLE)      -      -
    5      4      6      INDEX UNIQUE SCAN SYS_C0072201 (INDEX (UNIQUE))      2      1
    6      3      5      NESTED LOOPS      -      -
    7      6      6      BUFFER SORT      -      -
    8      7      7      CONNECT BY PUMP      -      -
    9      6      6      TABLE ACCESS BY INDEX ROWID PRODUCTELEMENTIMPL (TABLE)      19      49
    10      9      7      INDEX RANGE SCAN PRODUCTELEMENTIMPL_IDX1 (INDEX)      3      49
    11      3      5      TABLE ACCESS FULL PRODUCTELEMENTIMPL (TABLE)      19      49
    Slow:
    ID PARENT_ID LEVEL SQL Kosten Anzahl Zeilen
    0 1 SELECT STATEMENT 1 1
    1 0 2 HASH UNIQUE 1 1
    2 1 3 FILTER
    3 2 4 CONNECT BY WITHOUT FILTERING
    4 3 5 TABLE ACCESS BY INDEX ROW 3 1
    ID PRODUCTELEMENTIMPL (TABLE)
    5 4 6 INDEX UNIQUE SCAN SYS_C0 2 1
    020528 (INDEX (UNIQUE))
    6 3 5 TABLE ACCESS FULL PRODUCT 6628 1100613
    ELEMENTIMPL (TABLE)
    Any ideas how to avoid this full table scan?
    bye
    Roland Spatzenegger

    Hello,
    thank you for your replies. The indices and table schemas are the "same", but only the content for the tables was mirrored.
    We made some tests with dropping and/or analyzing the tables, but it didn't change anything.
    The main problem is that the query takes 33s in the productive environment for searching in a couple of rows. At the moment it's faster to make
    SELECT DISTINCT P.ID, P.STATE FROM PRODUCTELEMENTIMPL P WHERE ( ( LABEL = 'SomeLabel' AND PRODUCTELEMENTTYPE = 'SomeText' ) ) START WITH P.ID = 42 CONNECT BY PRIOR P.ID = P.PARENT
    and to test in the application if the state-values match ;-)
    If I add the hint /*+ no_filtering */ in the test environment, I get the same "slow" execution path as in the production environment. So the question is, what prevents the filtering in "connect by"?
    (I think in the fast version it filters only the results of the hierarchical query, in the slow version it first filters the whole table and joins/merge it with the hierachical result).
    bye
    Roland Spatzenegger

  • Problem creating a hierarchical tree in forms builder[issue with the query]

    Hi all,
    I have 2 tables.
    box (box_id, box_name)
    item(item_id, item_name, box_id)
    In a box there are several items.
    I want to create a hierachical tree to display items that are present in each box.
    LIKE:
    |---BOX1
    | |----ITEM 1
    | |----ITEM 2
    |
    |---BOX2
    | |----ITEM 1
    | |----ITEM 2
    Currently i am trying this query:
    SELECT -1 state, box_name, 'icon' icon, box_id val
    from box b, item i;
    I don't know what value to put for level, i don't know how to code the 'connect by prior' part.
    Could you please advise me?
    Michaël.
    PS. Then i will eventually use this query in forms builder.

    Hi MichaelR
    i get the FRM - 47321 error in forms builder ..
    Hence In order to populate a tree, the Select order must retrieve 5 columns:
    STATUS, LEVEL, LABEL, ICON, VALUE u should notice this orders in ur Query this will solve the error and pls notice that the...
    My advice is to use the On Line help in ur forms builder to help u in this ...
    Initial state : number
    Node tree depth : number
    Label for the node : varchar2
    Icon for the node : varchar2
    Data : varchar2This should be in WHEN-NEW-FORM-INSTANCE-trigger in order to populate ur tree...
    another thing why don't u think of building ur tree as i did here in the following example...Pls have a look here ....
    Hope this helps...
    Regards,
    Amatu Allah.

Maybe you are looking for