Hierarchical query with where clause

Hi,
How can I query hierarchically a query with WHERE clause? I have a table with three fields session_id,id and root_id.
When I try with the following query,
select id, level from relation
where session_id = 79977
connect by prior id = root_id start with id = 5042;
It gets duplicate values.
I want the query to show in the hierarchical manner with a filter condition using WHERE clause. Please help me how can I achieve this. If you know any link that describes more about this, please send it.
Thanks in Advance.
Regards,
-Parmy

Hi Sridhar Murthy an others,
Thanks a lot for your/the answer. It's working for me. It saved a lot of other work around without the proper knowledge of hierarchical query. Please send me any link that describes these issues in detail and also I hope as I have mentioned in the other message, same cannot be achieved on views or ( on two different tables ???)
Any way thanks for your reply,
It's working for me.
With happiness,
-Parmy

Similar Messages

  • Populate list by executing query with where clause

    Hi,
    I m populating my list from database table using following command.
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("learning", new HashMap());
    EntityManager em = emf.createEntityManager();
    String query = "select d from Dept d";
    List list = em.createQuery(query).getResultList();
    My list is getting populated with all of rows in my database table(dept). The problem is, I cant use where clause in my query string.
    String query = "select d from Dept d where d.dept_name='ANYNAME'";
    Moreover I cant select even indivisual columns by using following line
    String query = "select d.dept_code,d.dept_name from Dept d";
    It looks like that my query is getting all rows from table as Object.
    What to do to
    1. put some where clause
    2. get some particular colums instead of all columns
    3. apply some table joins in query
    plz help.

    Hi Alex,
    I misunderstood your question. You had mentioned "My list is getting populated with all of rows in my database table(dept). The problem is, I cant use where clause in my query string. "
    I thought you might not have permissions to modify the code in the class, and that's why I suggested that you could write new classes.
    1) write new classes,? means if I need just two columns from a table >(instead of all columns), do I need to write new class with just two >columns (getters and setters)?You can write a SQL statement anyway you want , there are no restrictions in JDBC , so if you need just 2 columns you can write a custom query for that.
    "select column1 as a, column2 as be from table_name where column3 = xyz" etc.
    2) Is not anyway to write SQL statement like
    select dept_code,dept_name from dept where dept_name='anything'The above SQL is correct, it should work.
    3) Stored procedures? can I get some example(code) to get an idea >how to implement complex queries with where clause and joinings >using stored procedures?Stored procedures are specific to the database you are using, Oracle has a particular syntax for store procdures.
    You can call stored procedures from JDBC also, search on Google for
    "Calling stored procedures from JDBC"
    4) I m using hibernate. can I get any example of using hibernate own >query?Tutorial on Hibernate Query Language:
    http://www.hibernate.org/hib_docs/v3/reference/en/html/queryhql.html

  • Issue in select query with where clause

    Hi guys,
    I'm facing an issue while using select query with the where clause. When I'm selecting all the data from the table it returns the correct result. But when I'm using the where clause to get the specific rows from the table it returns no rows. But the data I'm trying to fetch using the where condition exists in the table.
    Here is my query which causing the issue,
    select * from mytable where myfield = 'myvalue'
    But if I use the following query it returns the result correctly.
    select * from mytable
    Also the myfield value 'myvalue' exists in the table.
    I have tried by running this query in both SQL Developer and SQL Plus. I have tried this query in mssql as well. It works perfectly and returns correct result sets for both the queries I have mentioned above. I'm unable to predict the issue as I'm new to ORACLE. Please help.
    Thanks,
    Ram.

    Hi Ram,
    I experienced an issue similar to this with a varchar2 field. Some of our records had a hidden newline character at the end of them, which was making queries like the one below fail:
    select * from employees
    where email = '[email protected]'The best way I found to detect this was to use
    select 'XX'||email||'XX' from employeesTo make sure that there were no newlines. But that is just a guess. If you could provide some example table data and the outputs of your selects, it would be helpful.
    Jeff

  • Query Bean Where clause

    In Query Bean (Auto Customization Criteria) , OA FWK generate
    where clause automatically .
    I want to disable this criteria in some cases. Is there any way exists?
    (Disable means remove some condition )
    I want to see runtime query with where clause(In case of Query Bean) . Is there is any way to find out it?
    Thanks, Avaneesh

    You have couple of options to do this,
    1. You can use getCriteria API on the queryBean which will stop the query execution by framework and it's the responsibility of the developer to use the dictionary returned by getCriteria and bind the complete where clause yourself.
    2. You can use getNonViewAttrCriteria API on queryBean. This provides a dictionary of criteria on the column which are not mapped to a viewAttribute, for example if you want a poplist in the search region which has values like "Last one week", "Last 2 weeks", "Last 15 days" and so on and want to bind the criteria your self by interpreting the value selected.
    In this case, framework still binds the where clause for the other criteria's which are mapped to a vo based column in the table and expects the developer to bind the criteria for these non viewattribute mappings in the controller.
    I think your requirement fits in the second approach.

  • Export (expdp) with where clause

    Hello Gurus,
    I am trying to export with where clause. I am getting below error.
    Here is my export command.
    expdp "'/ as sysdba'" tables = USER1.TABLE1 directory=DATA_PUMP dumpfile=TABLE1.dmp logfile=TABLE1.log query= “USER1.TABLE1:where auditdate>'01-JAN-10'” Here is error
    [keeth]DB1 /oracle/data_15/db1> DATA_PUMP dumpfile=TABLE1.dmp logfile=TABLE1.log query= USER1.TABLE1:where auditdate>'01-JAN-10'                    <
    Export: Release 11.2.0.3.0 - Production on Tue Mar 26 03:03:26 2013
    Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.
    Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Starting "SYS"."SYS_EXPORT_TABLE_03":  "/******** AS SYSDBA" tables=USER1.TABLE1 directory=DATA_PUMP dumpfile=TABLE1.dmp logfile=TABLE1.log query= USER1.TABLE1:where auditdate
    Estimate in progress using BLOCKS method...
    Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
    Total estimation using BLOCKS method: 386 MB
    Processing object type TABLE_EXPORT/TABLE/TABLE
    Processing object type TABLE_EXPORT/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
    Processing object type TABLE_EXPORT/TABLE/INDEX/INDEX
    Processing object type TABLE_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
    Processing object type TABLE_EXPORT/TABLE/TRIGGER
    Processing object type TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
    ORA-31693: Table data object "USER1"."TABLE1" failed to load/unload and is being skipped due to error:
    ORA-00933: SQL command not properly ended
    Master table "SYS"."SYS_EXPORT_TABLE_03" successfully loaded/unloaded
    Dump file set for SYS.SYS_EXPORT_TABLE_03 is:
      /oracle/data_15/db1/TABLE1.dmp
    Job "SYS"."SYS_EXPORT_TABLE_03" completed with 1 error(s) at 03:03:58Version
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for IBM/AIX RISC System/6000: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production

    Hello,
    You should use parameter file.Another question i can see you are using 11g.Why don't you use data pump?.
    Data Pump is faster and have more features and enhancement than regular imp and exp.
    You can do the following:
    sqlplus / as sysdba
    Create directory DPUMP_DIR3  for 'Type here your os path that you want to export to';then touch a file:
    touch par.txt
    In this file type the following the following :
    tables=schema.table_name
    dumpfile=yourdump.dmp
    DIRECTORY=DPUMP_DIR3
    logfile=Your_logfile.log
    QUERY =abs.texp:"where hiredate>'01-JAN-13' "then do the following
    expdp username/password parfile='par.txt'
    If you will import from Oracle 11g to version 10g then you have to addthe parameter "version=10" to the parameter file above
    BR
    Mohamed ELAzab
    http://mohamedelazab.blogspot.com/

  • Outer Join with Where Clause in LTS

    HI all,
    I have a requirement like this in ANSI SQL:
    select p1.product_id, p1.product_name, p2.product_group
    from product p1 left outer join product_group p2 on p1.product_id = p2.product_id
    and p2.product_group = 'NEW'
    In Regular SQL:
    select p1.product_id, p1.product_name, p2.product_group
    from product p1, product_group p2
    WHERE p1.product_id *= p2.product_id and p2.product_group = 'NEW'
    In OBIEE, I am using a left outer join between these two in Logical table Source, and also, Gave
    p2.product_group = 'NEW' in WHERE clause of LTS.
    This doesn't seem to solve purpose.
    Do you have any idea how to convert WHERE clause in physical query that OBIEE is generating to something like
    product p1 left outer join product_group p2 on p1.product_id = p2.product_id AND p2.product_group = 'NEW'
    I am using Version 10.1.3.4.1
    Creating an Opaque view would be my last option though.

    Hello
    I have read your post and the responses as well. and I understand that you have issues with the Outer Join with where Clause in LTS.
    Try this solution which worked for me (using your example ) -
    1. In the Physical Layer created a Complex join between PRODUCT and PRODUCT_GROUP tables and use this join relationship :
    PRODUCT.PROD_ID = PRODUCT_GROUP.PROD_ID  AND  PRODUCT_GROUP.GROUP_NAME = 'MECHANICAL' 
    2. In the General Tab of PRODUCT table LTS add PRODUCT_GROUP  table and select Join Type as Left Outer Join.
    3. Check Consistency and make sure there are no errors .
    when you run a request you should see the following query generated -
    select distinct T26908.PROD_ID as c1,
         T26908.PROD_NAME as c2,
         T26912.GROUP_NAME as c3
    from
         PRODUCT T26908 left outer join PRODUCT_GROUP T26912 On T26908.PROD_ID = T26912.PROD_ID and T26912.GROUP_NAME = 'MECHANICAL'
    order by c1, c2, c3
    Hope this works for you. If it does please mark this response as 'Correct' .
    Good Luck.

  • Require a query with all clauses

    Hi All,
    I have been asked for a query to write by using all sql clauses like group by, where, having, order by in a single query. I just wrote the below query but I did not get out put. Please do correct where I am missing.
    select deptno, max(sal) from emp group by deptno having  deptno > ( select distinct deptno from emp where deptno >= 20)
    Thanks for your time and info.

    1007912 wrote:
    select deptno, max(sal) from emp group by deptno having  deptno > ( select distinct deptno from emp where deptno >= 20)
    Logically it was wrong; as your sub-query will return more then one record for comparison. By the way if you are querying the same data from same table then why you need a sub query in having clause! No need of it. Even if you are not using any aggregate predicates then use it with where clause.
    This is how your query and output should come out!
    SQL> select
      2   deptno, max(sal)
      3  from emp
      4  where deptno >= 20
      5  group by deptno
      6  order by 1
      7  /
        DEPTNO   MAX(SAL)
            20       3000
            30       2850
    SQL>

  • Outer join on query with OR clause

    hi all, i am having problem outerjoining a query with or clause
    here is my data
    WITH table1 AS
    SELECT  'test' txt1, 'pak' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
    SELECT  null txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
    SELECT  null txt1, NULL txt2, 'ced3' txt3, 'su3' txt4 FROM dual UNION ALL
    SELECT  null txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
    SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
    SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual
    ,table2 AS
    SELECT 111 pid, 'test' txt1, 'pak4' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
    SELECT 222 pid, 'test1' txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
    SELECT 333 pid, 'test2' txt1, 'pak3' txt2, 'ced3' txt3, 'su4' txt4 FROM dual UNION ALL
      SELECT 444 pid, 'test2' txt1, 'pak3' txt2, 'ced4' txt3, 'su3' txt4 FROM dual
    SELECT b.pid, a.*
    from table1 a, table2 b
    WHERE (a.txt1 = b.txt1 OR
           a.txt1 IS NULL AND a.txt2=b.txt2 OR
           Nvl(a.txt2, a.txt1) IS NULL AND a.txt3 = b.txt3 OR
           Nvl(a.txt2, a.txt1) IS NULL  AND a.txt3 IS NULL AND a.txt4 = b.txt4
           ) as you can see i am joining table1 and table 2. i am joining with txt1, if txt1 is null then join by txt2, if null then join by txt3 and so on.
    the code above product this output
    PID     TXT1     TXT2     TXT3     TXT4
    ===     ====     ===   ==== ====
    111     test     pak      ced     su
    222             pak      ced2     su2
    333                     ced3     su3
    444                          su3this output is partially correct. only 4 rows were display and two was left out
    SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
    SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual i tried using outer join but oracle complain that i cannot use outerjoin with OR clause.
    can someone help modify my query to display the output below ?
    PID     TXT1     TXT2     TXT3     TXT4
    ===    ====      ===   ====  ====
    111     test     pak      ced     su
    222             pak      ced2     su2
    333                     ced3     su3
    444                          su3
    NULL  NULL   NULL    NULL   NULL
         test5

    Not sure you can do it with the Oracle style outer joins, but wioth ANSI style joins it is simple, actually exactly as you had it.
    SQL> set null null;
    SQL> WITH table1 AS (
      2   SELECT  'test' txt1, 'pak' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
      3   SELECT  null txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
      4   SELECT  null txt1, NULL txt2, 'ced3' txt3, 'su3' txt4 FROM dual UNION ALL
      5   SELECT  null txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
      6   SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
      7   SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual),
      8  table2 AS (
      9   SELECT 111 pid, 'test' txt1, 'pak4' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
    10   SELECT 222 pid, 'test1' txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
    11   SELECT 333 pid, 'test2' txt1, 'pak3' txt2, 'ced3' txt3, 'su4' txt4 FROM dual UNION ALL
    12   SELECT 444 pid, 'test2' txt1, 'pak3' txt2, 'ced4' txt3, 'su3' txt4 FROM dual)
    13  SELECT b.pid, a.*
    14  from table1 a
    15     LEFT JOIN table2 b
    16        ON (a.txt1 = b.txt1 OR
    17            a.txt1 IS NULL AND a.txt2=b.txt2 OR
    18            Nvl(a.txt2, a.txt1) IS NULL AND a.txt3 = b.txt3 OR
    19            Nvl(a.txt2, a.txt1) IS NULL  AND a.txt3 IS NULL AND a.txt4 = b.txt4);
           PID TXT1   TXT2   TXT3   TXT4
           111 test   pak    ced    su
           222 null   pak    ced2   su2
           333 null   null   ced3   su3
           444 null   null   null   su3
    null       text5  null   null   su3
    null       null   null   null   nullJohn

  • Query using where clause

    I am not able to run a SQL query using where clause.
    the query is as follows:
    I extract the text input by the user in a text field say 'a' and
    store it in string 'y'.
    String y= a.getText();
    //running the query
    Select A from B where B.x=y;
    how do we run a where clause when y is a string variable instead of value?

    Use the following :
    String y = a.getText();
    String query ="select A.CODE from Port A where A.NAME=" + "'" + y + "'" ;
    ResultSet rs= stmt.executeQuery(query);

  • Merge with where clause after matched and unmatched

    Hai,
    Can anybody give me one example of merge statement with
    where clause after matched condition and after the unmatched condition.
    MERGE INTO V1 VV1
    USING (SELECT     A.CNO XXCNO, A.SUNITS XXSU, A.DDATE XXDD, XX.SUM_UNITS SUMMED
    FROM V1 A,
    (SELECT                
    SUM(SUNITS) SUM_UNITS FROM V1 B                                   
    GROUP BY CNO) c
    WHERE
    A.DDATE=0 AND A.SUNITS <>0 AND
    A.ROWID=(SELECT MAX(ROWID) FROM V1 )) XX
    ON (1=1)
    WHEN MATCHED THEN UPDATE SET
    VV1.SUNITS=XX.SUMMED
    WHERE XX.XXDD=0
    WHEN NOT MATCHED THEN INSERT
    (VV1.CNO, VV1.SUNITS, VV1.SUNITS)
    VALUES (XX.XXCNO, XX.XXSU, XX.XXDD)
    WHERE XX.XXDD<>0
    i am getting the error
    WHERE XX.XXDD=0
    ERROR at line 13:
    ORA-00905: missing keyword
    Thanks,
    Pal

    One of the example is there:
    http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10759/statements_9016.htm#sthref7014
    What Oracle version do you use ?
    Besides the condition (1=1) is non-deterministic,
    I would expect there an exception like "unable to get a stable set of rows".
    Rgds.

  • Insert with Where Clause

    Hi,
    Can we write Insert with 'Where' clause? I'm looking for something similar to the below one (which is giving me an error)
    insert into PS_AUDIT_OUT (AUDIT_ID, EMPLID, RECNAME, FIELDNAME, MATCHVAL, ERRORMSG)
    Values ('1','10000139','NAMES','FIRST_NAME',';','')
    Where AUDIT_ID IN
    (  select AUDIT_ID from PS_AUDIT_FLD where AUDIT_ID ='1' and RECNAME ='NAMES'
    AND FIELDNAME = 'FIRST_NAME' AND MATCHVAL = ';' );
    Thanks
    Durai

    It is not clear what are you trying to do, but it looks like:
    insert
      into PS_AUDIT_OUT(
                        AUDIT_ID,
                        EMPLID,
                        RECNAME,
                        FIELDNAME,
                        MATCHVAL,
                        ERRORMSG
    select  '1',
            '10000139',
            'NAMES',
            'FIRST_NAME',
      from  PS_AUDIT_FLD
      where AUDIT_ID = '1'
        and RECNAME ='NAMES'
        and FIELDNAME = 'FIRST_NAME'
        and MATCHVAL = ';'
    SY.

  • Hosting company does not support SQL query with OUTFILE clause

    From my mysql database, I want to allow the user to run a query and produce a csv / text file of our membership database.   Unfortunately,  I just found out my hosting company does not support the SQL query with OUTFILE clause for MySQL database.
    Are there any other options available to produce a file besides me running the query in phpadmin and making the file available to users.
    Thanks.  George

    Maybe this external Export Mysql data to CSV - PHP tutorial will be of help
    Cheers,
    Günter

  • The issue with using the multiple columns sub-query in WHERE clause

    Hi All,
    my database version is 10.2.
    the problem i am trying to deal with is that when I use multiple column sub-query in the WHERE clause of the SELECT statement, the actual row number returned from the sub-query is different from the whole statement.
    And what I found is that, whenever there is NULL in any of those columns returned from the SUB-QUERY, the outer query will just return NULL for that whole row.
    Here is an example:
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t;
    7782     CLARK     MANAGER     7839     09-JUN-81     2450     10
    7839     KING     PRESIDENT  NULL  17-NOV-81     5000     10
    7934     MILLER     CLERK     7782     23-JAN-82     1300     10
    select * from EMP where (EMPNO, ENAME, job, MGR, HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     If I specifically deal with the NULL situations for the columns which might return NULL, I can get the result right.
    select * from EMP where (EMPNO, ENAME, job, NVL(MGR,-1), HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, nvl(mgr,-1), hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  nvl(mgr,-1), hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7839     KING     PRESIDENT  null   17-NOV-81     5000          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     the problem is that, I feel this is a very lame way of handling it.
    So, I wonder or am asking if there is any better or standard way to do it?
    any help would be highly appreciated.
    Thanks

    Hi,
    As you discovered, INTERSECT treats NULL as a value, but IN does not.
    What you did with NVL is one way to handle the situation. If there was a chance that any of the columns could be NULL, then you might prefer something like this:
    select      *
    from      EMP
    where      ( EMPNO      || '~' ||
           ENAME      || '~' ||
           job           || '~' ||
           MGR           || '~' ||
           TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')
                    || '~' ||
           SAL           || '~' ||
           DEPTNO
         ) in (
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from     emp
             intersect
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from      t
             );This assumes that you can identify some string (I used '~') that never occurs in the strings in these tables.
    This is implicitly converting the NUMBERs. That's usually not a good thing to do. but explicitly converting them would make this even more tedious.
    You should explicitly convert any DATEs to strings, however. Depending on your default format, and your data, you might get away with implicit conversions even for DATEs, but don't bet on it.
    If you had to do this often, you might consider writing a user-defined function:
    delimited_string (empno, ename, job, mgr, hiredate, sal, deptno) would return a string like
    '7839~KING~PRESIDENT~~17-NOV-1981~5000~10'
    This will make the coding easier, but beware: it will make the execution slower.

  • 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
    ;

  • No tree displayed with WHERE clause (data issue?)

    I tried this on the apex.oracle.com workspace after it didnt run in our setup, and I ran into the same issue.
    I cant get the tree to display when I add a WHERE clause to the query.
    I know this isnt a problem with the WHERE clause, and has something to do with the data.
    If I just delete the data I dont want from the table (data_type <> 'S'), it WORKS, even with the WHERE clause.
    I have checked running the SQL, and the root element is returned.
    When I look at the HTML source of the page, I can see the js object created, though it seems to be constructed incorrectly.
    select case when connect_by_isleaf = 1 then 0
    when level = 1 then 1
    else -1
    end as status,
    level,
    "DATA_TEXT" as title,
    null as icon,
    "ID" as value,
    null as tooltip,
    null as link
    from "#OWNER#"."T_ROOT_CAUSE_TEMPLATE"
    where (data_type='S' or id=346)
    start with id=346
    connect by prior "ID" = "PARENT"
    order siblings by "DATA_SEQUENCE"

    Just in case if you didn't know it, you can use WITH factoring clause when creating a tree. It makes it possible to create as many "tables" as you need, while the final hierarchical query (that is responsible for the way the tree looks like) is a simple one. This (+WITH+) approach is convenient as you can avoid repeating inline views and/or subqueries.
    For example, your query might have looked like this:
    with s_type as
      (select * from t_template
       where data_type = 'S'
          or id = 346
    select
      case when connect_by_isleaf = 1 then 0
           when level = 1 then 1
           else -1
      end as status,
      level,
      data_text as title,
      null as icon,
      id as value,
      null as tooltip,
      null as link
    from
      s_type
    start with id=346
    connect by prior id = parent
    order siblings by data_sequence

Maybe you are looking for

  • Unable to map the portal user with back end user through web dynpro coding

    Hi All, I 've a portal user which is mapped to back end user by  system in the portal. i 'm able to get the portal user from web dynpro application. But unable to get the mapped back end user this is my code String systemalias = "SAP_CRM_PROD"; Map m

  • Open external URL from Homepage Framework

    Hi, We are building our new ESS functionality with Homepage Framework and I need to create some links to external URL. I would like them to open in a different window with no portal header at all. They should appear as services listed in the menu are

  • Camera raw 7.1

    I have Photoshop CS6 and want the Camera Raw filter from the dropdwon menu back.  How can I install Camera Raw 7.1 over the latest version that is 8 and does not have the filter? (amongst other things)

  • Any fix for not playing swf files?

    Hello Having trouble getting FF to play my Flash 8 swf files on this page http://www.enhancedwireless.net/indexrdm.html There should be a small logo animated for about 3 sec in the upper left of this page, but instead I get nothing on my MAC OS 10.3.

  • Secret hidden certificate - cannot delete!

    Hello, I have an old identity certificate used for 802.1x authentication that is "stuck" inside the device; when I setup a new 802.1x network connection, I can select TLS/Certificate and then the identity shows up but I can never remove the certifica