Hierarchical query - CONNECT BY and result in different columns.

Hi everyone,
I have a small question, hoping that someone can help me. As you will see, this
is not very important. It's just me wondering if I can learn something in SQL.
Let's suppose I have an ORGANIZATIONS table:
CREATE TABLE ORGANIZATIONS (
  ID_ORGANISATION NUMBER(10) PRIMARY KEY,
  NAME VARCHAR2(255) NOT NULL,
  ID_PARENT_ORGANIZATION NUMBER(10)
INSERT INTO ORGANIZATIONS(1, 'Parent of all', null);
INSERT INTO ORGANIZATIONS(11, 'Child 11', 1);
INSERT INTO ORGANIZATIONS(111, 'Child 111', 11);
INSERT INTO ORGANIZATIONS(112, 'Child 112', 12);
INSERT INTO ORGANIZATIONS(12, 'Child 12', 1);
INSERT INTO ORGANIZATIONS(121, 'Child 121', 12);Let's also assume that we can have an undefined number of levels.
Now, my question:
With a query like
SELECT LPAD(' ', LEVEL) || NAME  as conc
  FROM ORGANIZATIONS
START WITH ID_ORGANIZATION = 1
CONNECT BY PRIOR ID_ORGANISATION = ID_PARENT_ORGANIZATION
..I have a result like
[conc]
"Parent of all"
   "Child 11"
     "Child 111"
     "Child 112"
   "Child 12"
   ...All in one columns.
What I'd like is a result like this one:
[LEVEL_1]         [LEVEL_2]      [LEVEL_3]
"Parent of all"
                  "Child 11"
                                 "Child 111"
                                 "Child 112"
                  "Child 12"
                                 "Child 121"I'd like to have this structure for the 5 first levels. Do you think this is possible or not?
Thanks for your advice,

user13117585 wrote:
I'd like to have this structure for the 5 first levels. Do you think this is possible or not?Yes, something like...
SQL> ed
Wrote file afiedt.buf
  1  SELECT DECODE(LEVEL,1,NAME) as conc1
  2        ,DECODE(LEVEL,2,NAME) as conc2
  3        ,DECODE(LEVEL,3,NAME) as conc3
  4        ,DECODE(LEVEL,4,NAME) as conc4
  5        ,DECODE(LEVEL,5,NAME) as conc5
  6        ,DECODE(LEVEL,6,NAME) as conc6
  7  FROM ORGANIZATIONS
  8  START WITH ID_ORGANISATION = 1
  9* CONNECT BY PRIOR ID_ORGANISATION = ID_PARENT_ORGANIZATION
SQL> /
CONC1                CONC2                CONC3                CONC4                CONC5             CONC6
Parent of all
                     Child 11
                                          Child 111
                     Child 12
                                          Child 112
                                          Child 121
6 rows selected.
SQL>Just add levels as you need them.

Similar Messages

  • Usability of Connection Managers and Packages across different development users

    Hi All,
    I am new to SSIS. Currently we are doing the development in SSIS 2012 using the SQL Server Data Tools and there are two different Windows users who login to the server to work on SQL Server Data Tools.
    We have created one SSIS project and under that project we have created two different OLE DB Connection Managers to connect to the same database. We had to create two different Connection Managers as the Windows users were not able to connect to the DB using
    the connection manager created by the other user and users are also not able to execute packages created by the other user. The packages were developed with Protection Level set as "EncryptSensitiveWithUserKey". 
    Now at the end of development and before moving onto the testing phase, we have to integrate the packages that should run on a single Connection Manager. The Windows user should be able to run the SSIS packages using a single connection manager and also
    be able to execute the packages created by the other user.
    My question may sound silly. But since I am relatively new to SSIS, I need your help on above and also the steps for configuration and settings for deployment.
    Thanks in advance!
    Abhishek

    Hi Abhishek,
    If I understand correctly, a Windows user cannot be able to connect to the DB using the connection manager created by the other user and the user also cannot be able to execute packages created by the other user when the packages were developed with Protection
    Level set as "EncryptSensitiveWithUserKey".
    This behavior is by design. In an Integration Services package, the following information is defined as sensitive:
    The password part of a connection string.
    The task-generated XML nodes that are tagged as sensitive.
    Any variable that is marked as sensitive.
    EncryptSensitiveWithUserKey uses a key that is based on the current user profile to encrypt only the values of sensitive properties in the package. Only the same user who uses the same profile can load the package. If a different user opens the package, the
    sensitive information is replaced with blanks and the current user must provide new values for the sensitive data.
    To work around this issue, please refer to the following suggestions:
    If your issue is only related to the connection manager, we can use Windows Authentication log on the DB server. Then the other uses can still access to the DB and execute the package.
    Change the SSIS Package ProtectionLevel property to EncryptSensitiveWithPassword. This setting uses a password for encryption. To open the package in SSIS Designer (SSDT), the user must provide the package password.
    Use SSIS Package configuration files to store sensitive information, and then store these configuration files in a secured folder. You can then change the ProtectionLevel property to DontSaveSensitive so that the package is not encrypted and does not try
    to save secrets to the package. When you run the SSIS package, the required information is loaded from the configuration file. Make sure that the configuration files are adequately protected if they contain sensitive information.
    The following two documents are for your references:
    https://msdn.microsoft.com/en-us/library/ms141747.aspx
    https://support.microsoft.com/en-us/kb/918760
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • How to query a table and result together with autonumber

    Hi all
    How to query a table and the result return autonumber for each row together with the table values.
    I have tried rowid but it provide me with characters.
    Tj

    What is your exact requirement?
    If you want the number of rows selected, you can use rownum.
    select rownum, a.* from <table> a;
    Cheers
    Deepak

  • How to parse a delimited string and insert into different columns?

    Hi Experts,
    I need to parse a delimited string ':level1_value:level2_value:level3_value:...' to 'level1_value', 'level2_value', etc., and insert them into different columns of one table as one row:
    Table_Level (Level1, Level2, Level3, ...)
    I know I can use substr and instr to get level value one by one and insert into Table, but I'm wondering if there's better ways to do it?
    Thanks!

    user9954260 wrote:
    However, there is one tiny problem - the delimiter from the source system is a '|' When I replace your test query with | as delimiter instead of the : it fails. Interestingly, if I use ; it works. See below:
    with t as (
    select 'str1|str2|str3||str5|str6' x from dual union all
    select '|str2|str3|str4|str5|str6' from dual union all
    select 'str1|str2|str3|str4|str5|' from dual union all
    select 'str1|str2|||str5|str6' from dual)
    select x,
    regexp_replace(x,'^([^|]*).*$','\1') y1,
    regexp_replace(x,'^[^|]*|([^|]*).*$','\1') y2,
    regexp_replace(x,'^([^|]*|){2}([^|]*).*$','\2') y3,
    regexp_replace(x,'^([^|]*|){3}([^|]*).*$','\2') y4,
    regexp_replace(x,'^([^|]*|){4}([^|]*).*$','\2') y5,
    regexp_replace(x,'^([^|]*|){5}([^|]*).*$','\2') y6
    from t;
    The "bar" or "pipe" symbol is a special character, also called a metacharacter.
    If you want to use it as a literal in a regular expression, you will need to escape it with a backslash character (\).
    Here's the solution -
    test@ORA11G>
    test@ORA11G> --
    test@ORA11G> with t as (
      2    select 'str1|str2|str3||str5|str6' x from dual union all
      3    select '|str2|str3|str4|str5|str6' from dual union all
      4    select 'str1|str2|str3|str4|str5|' from dual union all
      5    select 'str1|str2|||str5|str6' from dual)
      6  --
      7  select x,
      8         regexp_replace(x,'^([^|]*).*$','\1') y1,
      9         regexp_replace(x,'^[^|]*\|([^|]*).*$','\1') y2,
    10         regexp_replace(x,'^([^|]*\|){2}([^|]*).*$','\2') y3,
    11         regexp_replace(x,'^([^|]*\|){3}([^|]*).*$','\2') y4,
    12         regexp_replace(x,'^([^|]*\|){4}([^|]*).*$','\2') y5,
    13         regexp_replace(x,'^([^|]*\|){5}([^|]*).*$','\2') y6
    14  from t;
    X                         Y1      Y2      Y3      Y4      Y5      Y6
    str1|str2|str3||str5|str6 str1    str2    str3            str5    str6
    |str2|str3|str4|str5|str6         str2    str3    str4    str5    str6
    str1|str2|str3|str4|str5| str1    str2    str3    str4    str5
    str1|str2|||str5|str6     str1    str2                    str5    str6
    4 rows selected.
    test@ORA11G>
    test@ORA11G>isotope
    PS - it works for semi-colon character ";" because it is not a metacharacter. So its literal value is considered by the regex engine for matching.
    Edited by: isotope on Feb 26, 2010 11:09 AM

  • How to show value and unit in different columns

    Hi All,
    I need ABAP help for the below requirement in BI7.0
    Data source contains  the field Amount in local currency (Data source is flat file of CSV format)
    Amount in local currency
           1000  INR
           2000  INR
           1000  GBP
           2000  EUR
    I have to get this value in target like below( value and unit should be in different columns)
    Amount in local currency              0currency
           1000                                           INR
           2000                                           INR
           1000                                           GBP
           2000                                           EUR
    Can any one help me how to declare the data type for  Amount in local currency and how to show this value in two columns in the target.
    Thanks,
    kishore.

    TYPES:BEGIN OF ty_stru,
      s1 TYPE string,
    END OF ty_stru,
    BEGIN OF ty_stru1,
      s2 TYPE string,
      s3 TYPE string,
      END OF ty_stru1.
    DATA:itab TYPE TABLE OF ty_stru,
          wa LIKE LINE OF itab.
    DATA:itab1 TYPE TABLE OF ty_stru1,
         wa1 LIKE LINE OF itab1.
    START-OF-SELECTION.
    "--Input--
    In input 1000 and USD having space
      wa-s1 = '1000 USD'.
       APPEND wa TO itab.
      wa-s1 = '1000 INR'.
       APPEND wa TO itab.
      wa-s1 = '1000 EUR'.
      APPEND wa TO itab.
    "--Input--
      LOOP AT itab INTO wa.
    SPLIT wa-s1 AT space INTO  wa1-s2 wa1-s3.*------> split command
    APPEND  wa1 TO itab1.*---------------->splited value store into another internal table
      ENDLOOP.
    "--Display--
      LOOP AT itab1 inTO wa1.
        WRITE: wa1-s2,
               wa1-s3.
      ENDLOOP.
    "--Display--
    Output:
    1000 USD
    1000 INR
    1000 EUR
    This is simple prgram for split a string into two different string based on space
    regards
    Dharma
    Edited by: dharma raj on Aug 19, 2009 2:01 PM

  • Compare data and return the different columns

    Good Afternoon,
    I am trying to compare the data in two tables and return only the columns and data where there is a difference.
    I have a compare script which checks every column in the two tables against each other, but as there are 200 columns in the tables it is tricky to see which column has a difference.
    So in my result set if coulum N is the differenct I would only want to return column N from both tables in the result set.
    I hope that this all makes sense?.

    Easiest way is to use tablediff utility for checking difference between tables
    see
    http://www.mssqltips.com/sqlservertip/1073/sql-server-tablediff-command-line-utility/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Hierarchical Query - Connect By clause

    Hi
    I've written a query using the Connect By clause to generate the table data in Tree structure with the appropriate levels.
    But Data might not correct such that it may have data which loops around. Like Table1 is parent of Table 2 and Table 2 is parent of Table 3 and Table 3 is again Parent of Table 1. If such incorrect Data exists then I'm getting Oracle Error "ORA-01436: CONNECT BY loop in user data" which is correct.
    What I need is, whenever this error message is raised I need to give my own error message instead of this Oracle error in SQL statement. Please note, I'm not using any PLSQL block, I just have one SQL statement. Appreciate any help on this subject. Thanks.

    Hi,
    Outside of PL/SQL, I don't know of any way to substitute your own error messages for the ones Oracle provides.
    In Oracle 10 (and up), you can write a query using the CONNECT_BY_ISCYCLE pseudo-column. Using CONNECT BY NOCYCLE, the query will never actually raise the ORA-01436 error, but you can get it to display your message in cases where it would have, had you not been using CONNECT BY NOCYCLE.
    Here's how to do it:
    Put your real query, plus CONNECT_BY_ISCYCLE, in the WITH-clause.
    Get the MAX (CONNECT_BY_ISCYCLE) from that sub-query. Let's call this max_cbi.
    Do a UNION ALL of two prongs:
    (1) SELECTs everything (except, pehaps, CONNECT_BY_ISCYCLE) from the sub-query, WHERE max_cbi = 0
    (2) SELECTs your "error message" from dual, WHERE max_cbi = 1.
    Edited by: Frank Kulash on Nov 26, 2008 2:09 PM

  • In Oracle 11g query, how can I refer to results of different column ....

    I want to be able to refer to the results of C1 in another column expression C2. I get ORA-00904: "C1" invalid identifier, which makes sense. I know that I can repeat the entire very long CASE again in my C2 DECODE, but wondering if I can save the server many extra cycles from evaluating the CASE again.
    SELECT [very long nested CASE statements] as C1, DECODE(C1,1,'YES','NO') as C2 FROM TABLE
    Many thanks,
    AK

    Hello
    You can't refer to the alias at the same level so you either have to repeat the CASE statement or wrap it in an inline view and refer to the alias in that. i.e.
    SELECT
        c1,
        DECODE(C1,1,'YES','NO') as C2
    FROM
            SELECT
                [very long nested CASE statements] as C1
            FROM
                FROM TABLE
        )HTH
    David

  • How to write a Query a table and the return result is the column name

    Hi All
    Pls advise how to write a query whereas the return result is the
    column name.
    I know there is describe <table_name>;
    Is there any other ways?
    Pls advise
    Tj
    Edited by: user600866 on Oct 14, 2008 12:13 AM

    Data Dictionary table user_tab_columns has all the column names. You can query that and get what ever you want.
    To get the column list of a table just query
    select *
      from user_tab_columns     
    where table_name = <your_table>Edited by: Karthick_Arp on Oct 14, 2008 12:18 AM

  • Sum two different columns from two different tables

    Can you select and sum two different columns, from two different tables in the same sql statement?
    i.e.
    table1
    Item----OnHand_Qty
    A--------10
    A--------15
    B--------10
    B--------10
    C--------20
    table2
    Item----Trx_Qty
    A--------2
    A--------4
    A--------6
    B--------1
    B--------1
    C--------4
    I'm looking for the following results from a query
    Item----Sum(Onhand_Qty)---Sum(Trx_Qty)
    A--------25

    Like this?
    SQL> create table table1 (item,onhand_qty)
      2  as
      3  select 'A', 10 from dual union all
      4  select 'A', 15 from dual union all
      5  select 'B', 10 from dual union all
      6  select 'B', 10 from dual union all
      7  select 'C', 20 from dual union all
      8  select 'D', 30 from dual
      9  /
    Tabel is aangemaakt.
    SQL> create table table2 (item, trx_qty)
      2  as
      3  select 'A', 2 from dual union all
      4  select 'A', 4 from dual union all
      5  select 'A', 6 from dual union all
      6  select 'B', 1 from dual union all
      7  select 'B', 1 from dual union all
      8  select 'C', 4 from dual union all
      9  select 'E', 3 from dual
    10  /
    Tabel is aangemaakt.
    SQL> select nvl(t1.item,t2.item) item
      2       , t1.sum_onhand_qty
      3       , t2.sum_trx_qty
      4    from ( select item, sum(onhand_qty) sum_onhand_qty
      5             from table1
      6            group by item
      7         ) t1
      8         full outer join
      9         ( select item, sum(trx_qty) sum_trx_qty
    10             from table2
    11            group by item
    12         ) t2
    13         on (t1.item = t2.item)
    14  /
    I SUM_ONHAND_QTY SUM_TRX_QTY
    A             25          12
    B             20           2
    C             20           4
    E                          3
    D             30
    5 rijen zijn geselecteerd.Regards,
    Rob.

  • 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

  • Too many results in hierarchically query

    Hello all,
    I'm searching for an idea to stop getting results 2, 3 and more times out of the following query
    select
    t.lvl,
    t.syswflvl,
    t.upper,
    LPAD(' ', (lvl)*8)||t.code code,
    LPAD(' ', (lvl)*8)||t.bezeichnung bezeichnung,
    t.chk,
    t.rang
    from (
    select '0' lvl, '0-'||to_char(syswftable,'0000000') syswflvl, '0- 0000000' upper, syscode code, bezeichnung, '' chk, 0 rang from wftable where (select count(wfm.syswftable) from wfm where wfm.syswftable = wftable.syswftable) > 0 union
    select '1' lvl, '1-'||to_char(syswfm,'0000000') syswflvl, '0-'||to_char(syswftable,'0000000') upper, syscode code, kurzbez bezeichnung, anzeigefilter chk, 1 rang from wfm union
    select '2' lvl, '2-'||to_char(syswfa,'0000000') syswflvl, '1-'||to_char(syswfm,'0000000') upper, syscode code, kurzbez bezeichnung, bedingung chk, rang from wfa union
    select '3' lvl, '3-'||to_char(syswfc,'0000000') syswflvl, '2-'||to_char(syswfa,'0000000') upper, syscode code, kurzbez bezeichnung, bedingung chk, rang from wfc union
    select '4' lvl, '4-'||to_char(syswfg,'0000000') syswflvl, '3-'||to_char(syswfc,'0000000') upper, syscode code, kurzbez bezeichnung, bedingung chk, rang from wfg
    ) t
    where ((t.chk not like '%and 0%'
    and trim(t.chk) not like '0%')
    or t.chk is null)
    and upper not like '%-'
    connect by nocycle prior syswflvl = upper
    order siblings by upper, syswflvl, rang
    What happens is, that I get the results from level 0 one times, from level 1 two times, from level 2 three times etc.
    What I'm try to achive is to get only the whole thing once.
    Hope you can see what my problem is ;-)
    Regards
    Carsten

    The effect of not having a start with clause in a hierarchical query is that a hierarchy is produced starting at every possible entry-point. So, you'll get the hierachy from node 1, the hierarchy from all nodes 2, the hierarchy from all nodes 3 and so one. Whether it starts with the correct one or not is not really relevant, as you already figured out that you get too much....
    So, just believe it, add a start with clause...and your problems are gone.

  • Hierarchical Query with Rollup Sum (CONNECT BY with GROUP BY ROLLUP)

    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS VALUES ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS VALUES ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS VALUES ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS VALUES ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS VALUES ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES VALUES ('4801001', 2000);
    INSERT INTO BALANCES VALUES ('4801002', 1000);
    INSERT INTO BALANCES VALUES ('4802001', 3000);
    INSERT INTO BALANCES VALUES ('4802002', 4000);What i need in this scenario is to run a hierarchical query, where for each node i compute the sum of all its children (In LEAF nodes which are the child accounts, this sum is the value in BALANCES itself). Final Result would be:
    TOT -> 10000
      ANA1 -> 3000
        4801001 -> 2000
        4801001 -> 1000
      ANA2 -> 7000
        4802001 -> 3000
        4802002 -> 4000I have tried various ways, and found out a workaround which works for a fixed amount of levels, basically it builds the hierarchy and computes the SYS_CONNECT_BY_PATH, then splits this as a regular expression and uses GROUP BY ROLLUP to compute the higher levels. Then i assemble it again, now with the computed values. Below is the example query:
    select level
        , NVL (vfinal.child_account,'TOTAL') ||' - '||
                            ( SELECT account_desc
                                FROM accounts
                               WHERE account_code = vfinal.child_acct ) account_name
         , to_char(sum_bal, 'fm999g999g999g990') as rolled_up_balance
      from
    select coalesce( princ.lvl3, princ.lvl2, princ.lvl1 ) child_acct
         , DECODE ( princ.lvl2 , NULL
                                     , NULL
                                     , DECODE ( princ.conta_lvl3, NULL
                                     , princ.conta_lvl1,princ.conta_lvl2 ) ) parent_acct
         , sum(princ.balance_amount) sum_bal
    from (
    select hier.lvl1
         , hier.lvl2
         , hier.lvl3
         , hier.parent_account
         , hier.account_code child_acc
         , bal.balance_amount
      from ( select level 
                  , sys_connect_by_path( account_code, '/' ) hierarchy_acct
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,3) lvl3
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,2) lvl2
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,1) lvl1
                  , account_code
                  , parent_account 
               from accounts acc
               where level <= 3
               start with parent_account is null
               connect by nocycle prior account = parent_account
               order siblings by parent_account
               ) hier
          , balances  bal
      where bal.cod_conta  = hier.account_code
    ) princ
    where princ.lvl1 is not null
    group by rollup ( princ.lvl1
                    , princ.lvl2
                    , princ.lvl3 )
    order by princ.conta_lvl1
           , princ.conta_lvl2
           , princ.conta_lvl3
    ) vfinal
    where child_acct is not null
    start with parent_acct is null
    connect by nocycle prior child_acct = parent_acctAll said and done, what i need is to do the same thing for infinite levels, because this query has 3 fixed levels. Do you know how can i structure a new query where, independently of the number of levels, the parent sums are all rolled up like this?
    Thanks a lot in advance! Best Regards!
    Thiago
    Edited by: Thiago on Sep 6, 2011 11:31 AM
    Edited by: Thiago on Sep 6, 2011 1:01 PM

    Hi,
    Thiago wrote:
    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES ('4801001', 2000);
    INSERT INTO BALANCES ('4801001', 1000);
    INSERT INTO BALANCES ('4802001', 3000);
    INSERT INTO BALANCES ('4802001', 4000);
    Thanks for posting the CREATE TABLE and INSERT statements. Remember why you do it: so that the people who want to help you can re-create the problem and test their ideas. If the statments don't work, then they are not so useful. None of the INSERT statements you posted work: they all need a VALUES keyword. Please test those statments before you post them.
    Also, make sure that the reuslts you post correspond to the sample data you post. In your sample data, there are no rows in balances for account_codes '4801002' or '4802002'.
    I think you want something like this:
    WITH  connect_by_results      AS
         SELECT     CONNECT_BY_ROOT account_code     AS root_account_code
         ,     account_code
         FROM     accounts
                             -- NOTE: No START WITH clause
         CONNECT BY     parent_account     = PRIOR account_code
    SELECT       c.root_account_code     || ' -> '
                          || TO_CHAR (SUM (b.balance_amount))     AS txt
    FROM           connect_by_results  c
    LEFT OUTER JOIN      balances          b  ON  c.account_code = b.account_code
    GROUP BY  c.root_account_code
    ;

  • Need to populate a hierarchical query results in detail block of WIPTXCFM

    Hi All,
    I would need to customize WIPTXCFM to populate all layered sub assembly schedule numbers against a Final Assembly schedule number.
    Requirement is as soon as User enter a FA schedule number; it should populate all levels Sub Assembly Schedule Numbers under this.
    I have thought of 1 approach; need suggestion if there is any better way to achieve this to improve the performance.
    My Approach: In custom WIPTXCFM form once the FA schedule number is entered; I can fetch all below level data(e.g Level1, level2 ...etc.)
    using a cursor with hierarchical query. Then loop through the cursor and insert them in the block after the FA record.
    So would look for your suggestion if there is any other better way to achieve this.
    Thanks in adv.
    Regards.

    880860 wrote:
    Hi All,
    I would need to customize WIPTXCFM to populate all layered sub assembly schedule numbers against a Final Assembly schedule number.
    Requirement is as soon as User enter a FA schedule number; it should populate all levels Sub Assembly Schedule Numbers under this.
    I have thought of 1 approach; need suggestion if there is any better way to achieve this to improve the performance.
    My Approach: In custom WIPTXCFM form once the FA schedule no is entered; I can fetch all below level data(e.g Level1, level2 ...etc.)
    using a cursor with hierarchical query. Then loop through the cursor and insert them in the block after the FA record.
    As per my findings; this hierarchical query takes longer to fetch the below levels data, around 1.5 mins.
    Hello 880860,
    If your are talking about EBS customization you can post at {forum:id=475}.
    Hope this helps

  • The risk analysis results are different when choose report type as "summary" and "management" summary

    Hello experts,
    I found a expired user with SOD conflicts in "management summary" report format, but it doesn't exist in "Summary" report. You can find the screenshot in attached file. The user name is "YINPENG2_BK".
    What happened? The result of different report formats are from different data source?
    Sincerely yours,
    Lynn

    Hi Lynn,
    that's not an issue from the system. It's more a handling issue as the results are splitted into several result sets. In management summary view you have only one result set as it's grouped by user and risk, whereas you have more than one in summary view (as you have multple entries for each user and risk).
    Change to the second, third, etc. result set and you will see the user in the list:
    Regards,
    Alessandro

Maybe you are looking for

  • IPhone 5 storage completely full and can't figure out to fix the problem?

    I got the iPhone 5c in August of last year. Previously, I had owned a flip-phone and only a flip-phone, so you can imagine that it was a big change. Though I know there is so much more that it can do (and so many things I have yet to discover), I mos

  • Submit Form Button Acrobat X Pro Mac

    I used Acrobat X Pro for the first time a couple of months ago. I created a form and when I was finished there was a Submit Form button in the purple field at the top of the document next to the Highlight Existing Fields button, and the text to the l

  • SQL Developer 3.0 data modeler print-to-pdf not working

    I am working in Windows XP. I am running SQL Developer version 3.0.04, which now includes a full-featured version of the Data Modeler. I have run into a problem with this version, which did not occur in the stand-alone version of the Data Modeler. Wh

  • Job logs from the original system after Unicode conversion.

    Dear Globalization experts, We are doing Unicode conversion and would like to know, if the Job logs from the batch jobs, executed before conversion (system with a 1100 code page), would be readable  in the Unicode system after the conversion.  We wil

  • Cant get my gift card to work

    hi i bought a 15 dollor i tunes gift card from petro canada in stewiacke and i put it on my iphone and it said that it wasent probly activated and to contact you guys