Need help with a self-join query

Hello
I have A table with the following data

OID parent_oid
4 of 10
4 2
2 2
12 6
6 6

parent_oid is the parent of the oid. I would like a query that displays the final parent of the oid. The result must indicate the following

Final parent OID
2 of 10
4 2
2 2
12 6
6 6

I use Oracle 10 g. I am familiar with free joins, but that alone will not do the job. Thank you!

Hello

arizona9952 wrote:
... I am familiar with free joins, but that alone will not do the job.

You are absolutely right!

A self-join 2-way would work for lines have no parent, or lines which are directly related to their final ancestor (such as the oid = 4), but not for what anyone further.
A 3-way self-join would work to a level more away from the last row, but no more. That would be enough with the small set of sample data that you posted, but it won't work if you have added a new rank parent_id = 10.
An N - way self-join would work for up to N + 1 levels, but no more.

You need something that can go to any number of levels, such as CONNECT BY:

SELECT     CONNECT_BY_ROOT oid     AS oid
,     parent_oid          AS final_parent
FROM     a
WHERE     CONNECT_BY_ISLEAF     = 1
CONNECT BY     oid     = PRIOR parent_oid
     AND     oid     != parent_oid
;

Published by: Frank Kulash, February 22, 2010 19:09

On sober reflection, I think that a request from top down, as one below, would be more effective than a motion up and down, like the one above:

SELECT     oid
,     CONNECT_BY_ROOT     parent_oid     AS final_parent
FROM     a
START WITH     parent_oid     = oid
CONNECT BY     parent_oid     = PRIOR oid
     AND     oid          != PRIOR oid
;

Tags: Database

Similar Questions

  • Need help with a self-join select the parent and child

    Hi all

    I have an OFFICE table that will hold the Oncology, district and division of the hierarchic is Oncology-district-> division >

    I want to list Oncology, district and division with its parent of the value of the following
    provinc     district      division
    
    A            NULL       NULL
    A            A.A         NULL
    A            A.A         A.A.A 
    -- Create table
    CREATE TABLE OFFICE
    (
      SLNO         VARCHAR2(20 BYTE),
      OFFICE_NAME  VARCHAR2(20 BYTE),
      PARENT_SLNO  VARCHAR2(20 BYTE),
      TYPE         VARCHAR2(2 BYTE)
    );
    
    ALTER TABLE OFFICE ADD (
      CONSTRAINT OFFICE_PK
      PRIMARY KEY
      (SLNO)
     );
    
    ALTER TABLE OFFICE ADD (
      CONSTRAINT P_C_FK 
      FOREIGN KEY (PARENT_SLNO) 
      REFERENCES OFFICE (SLNO));
    
    
    INSERT INTO OFFICE
      (SLNO, OFFICE_NAME, PARENT_SLNO, TYPE)
    VALUES
      ('1', 'A', NULL, 'PR');
    INSERT INTO OFFICE
      (SLNO, OFFICE_NAME, PARENT_SLNO, TYPE)
    VALUES
      ('2', 'A.A','1', 'DT');  
    INSERT INTO OFFICE
      (SLNO, OFFICE_NAME, PARENT_SLNO, TYPE)
    VALUES
      ('3', 'A.A.A', '2', 'DV');  
    I need your help.
    Thank you.

    Published by: Dipabkar Banik (DB) on June 13, 2011 12:17 AM

    Published by: Dipabkar Banik (DB) on June 13, 2011 12:18 AM

    Published by: Dipabkar Banik (DB) on June 13, 2011 06:45

    Published by: Dipabkar Banik (DB) on June 13, 2011 06:47

    Try this

    SELECT   CONNECT_BY_ROOT (office_name) provinc,
                 DECODE (LEVEL, 2, office_name, PRIOR office_name) district,
                 DECODE (LEVEL, 3, office_name) division
          FROM   office
    CONNECT BY   PRIOR slno = parent_slno
    START WITH   parent_slno IS NULL
    
  • Need help with the condition join in SQL

    Hi all -

    I need to ask for help with this query:

    Create table user_tab_col_test (varchar2 (30) from table_name, column_name varchar2 (30), data_type varchar2 (30));

    Insert into user_tab_col_test (table_name, column_name, data_type) values ('table1', 'column1', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('Column2', 'table1', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ("Column3", 'table1', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('column4', 'table1', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ("column1", "table2", 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('table2', 'column2', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('table2', "Column3", 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('table2', 'column4', 'varchar2')
    Commit;

    Create table all_cons_columns_test (varchar2 (30) from table_name, column_name varchar2 (30), constraint_name varchar2 (30))

    Insert into all_cons_columns_test (table_name, column_name, constraint_name) values ("table1", "column1", "primary")
    Insert into all_cons_columns_test (table_name, column_name, constraint_name) values ("table1", "column1", "secondary")
    Commit;

    This is my query and the current result:

    Select u.table_name, u.column_name, c.constraint_name
    Of user_tab_col_test u
    Outer join all_cons_columns_test c left
    On (u.table_name = c.table_name
    AND U.COLUMN_NAME = C.COLUMN_NAME
    AND C.CONSTRAINT_NAME IN ('main'))
    order of U.table_name, U.COLUMN_NAME;

    TABLE_NAME COLUMN_NAME, CONSTRAINT_NAME
    ------------------ --------------------- ----------------------------
    Table1 primary Column1
    Table1 Column2
    Table 1 Column3
    Table2 Column1
    Table2 Column2


    Three questions:
    (1) I don't want to return results where table_name = "table1". I can't get this to work.
    (2) is my proper request and this is the best way to return my desired results? For example, I want all of the columns of user_tab_col_test and I want to only display the constraint_name from all_cons_columns_test argument if the argument constraint_name = 'primary '.
    (3) will be the synatx be the same if I need to join a third table to all_cons_columns_test?

    Any advice/suggestions are appreciated-
    John

    Published by: user703358 on January 11, 2013 20:57

    Published by: user703358 on January 11, 2013 21:48

    Hi, John,.

    user703358 wrote:
    Hi all -

    I need to ask for help with this query:

    Create table user_tab_col_test (varchar2 (30) from table_name, column_name varchar2 (30), data_type varchar2 (30));

    Insert into user_tab_col_test (table_name, column_name, data_type) values ('table1', 'column1', 'varchar2')
    Insert into user_tab_col_test (table_name, column_name, data_type) values ('Column2', 'table1', 'varchar2')...

    Thanks for posting the CREATE TABLE and INSERT.
    It is more useful if you post the code that can be run without modification. You did not semicolons after INSERTION instructions.

    Three questions:
    (1) I don't want to return results where table_name = "table1". I can't get this to work.

    What have you tried? Post your best attempt.
    Here's one way:

    SELECT    u.table_name
    ,        u.column_name
    ,        c.constraint_name
    FROM             user_tab_col_test      u
    LEFT OUTER JOIN  all_cons_columns_test  c
                            ON    u.table_name     = c.table_name
                   AND   u.column_name     = c.column_name
                   AND   c.constraint_name IN ('primary')
    WHERE       u.table_name     = 'table1'          --  *****  NEW  *****
    ORDER BY  u.table_name
    ,            u.column_name
    ;
    

    You would not put this condition in the clause; who controls what is considered as a match between the tables, and "u LEFT OUTER JOIN c" means show all lines of u, even if they do not have a match in the c.

    (2) is my proper request and this is the best way to return my desired results? For example, I want all of the columns of user_tab_col_test and I want to only display the constraint_name from all_cons_columns_test argument if the argument constraint_name = 'primary '.

    Basically, this application is very well.
    It displays all the columns of user_tab_col_test; missing data_type. Just add u.data_type to the SELECT clause, or change the SELECT clause

    SELECT    u.*
    ,         c.constraint_name
    

    (3) will be the synatx be the same if I need to join a third table to all_cons_columns_test?

    Do you mean "" * add * one-third * column * to all_cons_columns_test '? "
    It depends on what results you want. Post new CREATE TABLE and INSERT and instructions the results you want new data.
    Most likely, the basic structure of what you've written will remain exactly the same.

  • Need help with the ANSI Join syntax

    Version: 11.1.0.7

    I have my select statement that returns 3000 lines and looks like
    select ..
    from tab1 a,tab2 b,tab3 c
    where a.c1=b.c1 and
    b.c2 = c.c2(+)
    and ...
    group by
    ..
    I want to convert it to ANSI SQL, because it must be able to Hibernate, and the developer says that Hibernate include only ANSI SQL. I tried something like
    select ..
    from tab1 a INNER JOIN tab2 b
    ON a.c1=b.c1 
    LEFT OUTER JOIN tab3 c
    ON b.c2=c.c2
    where ...
    group by
    ..
    I felt bad and it turned out to be the same. It returns no rows. Please help with the correct syntax.

    I'm not sure, sorry, because it's certainly the ANSI equivalent to the non-ANSI.

    Would you have examples of queries and data that you can reproduce the problem with, and that we could analyze?

    Published by: Seanmacgc on July 15, 2009 12:48

    If there is no Clause WHERE conditions in the original that are included in the ANSI version of the query in the WHERE Clause for the EXTERNAL table itself joined, then that could transform the JOIN JOIN internally, that is, all the filters on the EXTERNAL joined table should be included in the JOIN predicate - IT (b.c2 = c.2 AND c.c3 = 'X').

  • need help for an outer join query

    Hi friends...
    I have oracle 10g...
    I have a question which involve is joining three tables...

    the query is as follows:
    SELECT DISTINCT MU.MKT_ID                  "PAR ID",
                       MU.MKT_ID                  "ROOT ID",
                     MSU.SPEC_ID                "ID",
                   SU.SPEC_DESC                "DESC",
               SU.SPEC_CD          "SPEC CD"
    
                  FROM IPOADM_BATCH.MKT_UV1        MU,
                         IPOADM_BATCH.MKT_SPEC_UV1   MSU,
                 IPOADM_BATCH.SPEC_UV1       SU
    
                   WHERE MSU.MKT_ID  = MU.MKT_ID
               AND MSU.SPEC_ID = SU.SPEC_ID
             AND SU.SPEC_GRP_OR_CMPSTN_CD = 'C';
    in my front end application has some delete operations that removes specific data of the IPOADM_BATCH. MKT_SPEC_UV1 due to which the above query is nor fetch all rows.
    the relationship between the tables is clearly from the above query...

    I have the data in IPOADM_BATCH. MKT_UV1 and IPOADM_BATCH. Table of SPEC_UV1 after the delete operation

    now, I want the query above to retrieve data from IPOADM_BATCH. MKT_UV1 with small changes to the above query even if there is no data in IPOADM_BATCH. MKT_SPEC_UV1.

    I thought that if I use an outer join I can get it, but here I have to join three tables-join condition is based on the table that doesn't have a data...


    so please help me guys how can I change the query to get my desired out put...

    Hello

    There are several different things you could mean by it.

    Here's how to join the tables to get one of them:

    SELECT DISTINCT  mu.mkt_id                  "PAR ID",
                     mu.mkt_id                  "ROOT ID",
                     msu.spec_id                "ID",
                     su.spec_desc               "DESC",
                     su.spec_cd                   "SPEC CD"
    FROM           ipoadm_batch.mkt_uv1        mu
    LEFT OUTER JOIN      ipoadm_batch.mkt_spec_uv1   msu  ON   msu.mkt_id               = mu.mkt_id
    LEFT OUTER JOIN  ipoadm_batch.spec_uv1       su       ON   msu.spec_id              = su.spec_id
                                                  AND  su.spec_grp_or_cmpstn_cd = 'C'
    ;
    

    If it does not matter what it is that you want, and then after a small example of data (CREATE TABLE and INSERT, only relevant columns instructions) for all the tables and the results desired from these data.
    Highlight a few places where the above querry is the production of incorrect results of your sample data and explains how to get the correct results in these places.

  • [10g] need help with order by hierarchical query clause

    I have the following data samples:
    CREATE TABLE     bill_test1
    (     parent_part     CHAR(25)
    ,     child_part     CHAR(25)
    ,     line_nbr     NUMBER(5)
    ,     qty_per          NUMBER(9,5)
    );
    
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-10',100,1);
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-20',200,2);
    INSERT INTO bill_test1 VALUES ('ABC-1','ABC-30',300,3);
    INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-1',401,10);
    INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-2',402,5);
    INSERT INTO bill_test1 VALUES ('ABC-10','ABC-155',100,2);
    INSERT INTO bill_test1 VALUES ('ABC-10','HARDWARE-1',200,1);
    INSERT INTO bill_test1 VALUES ('ABC-155','RAW-2',100,4.8);
    INSERT INTO bill_test1 VALUES ('ABC-155','HARDWARE-3',200,3);
    INSERT INTO bill_test1 VALUES ('ABC-20','RAW-1',100,10.2);
    INSERT INTO bill_test1 VALUES ('ABC-30','RAW-3',100,3);
    And the following query gives me exactly what I want, in the order I want. However, I wonder if there is a way to get this order without creating the column SEQ, given that I don't need in my results
    SELECT     part_nbr
    ,     parent_part
    ,     child_part
    FROM     (
         SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
         ,     b.parent_part
         ,     b.child_part
         ,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
         FROM     bill_test1 b
         ,     dual
         CONNECT BY     parent_part     = PRIOR child_part
         )
    WHERE          part_nbr     = 'ABC-1'
    ORDER BY     seq
    ;
    
    Results of above query, except with SEQ included in SELECT (just to show what I'm sorting off of):
    PART_NBR                     PARENT_PART                  CHILD_PART                   SEQ
    ---------------------------- ---------------------------- ---------------------------- -----------------
    ABC-1                        ABC-1                        ABC-10                        100
    ABC-1                        ABC-10                       ABC-155                       100 100
    ABC-1                        ABC-155                      RAW-2                         100 100 100
    ABC-1                        ABC-155                      HARDWARE-3                    100 100 200
    ABC-1                        ABC-10                       HARDWARE-1                    100 200
    ABC-1                        ABC-1                        ABC-20                        200
    ABC-1                        ABC-20                       RAW-1                         200 100
    ABC-1                        ABC-1                        ABC-30                        300
    ABC-1                        ABC-30                       RAW-3                         300 100
    ABC-1                        ABC-1                        HARDWARE-1                    401
    ABC-1                        ABC-1                        HARDWARE-2                    402

    Hello

    As long as there is that a single root, brothers and SŒURS of ORDER BY, you say, but you can not do in a subquery (well, you can, but usually there is no interest in a subquery). If the CONNECT BY in a subquery, there is no guarantee that the main request will preserve the hierarchical order which provides the subquery.

    The query you posted does not require a query of Tahina, so you can say:

    SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
    ,     b.parent_part
    ,     b.child_part
    --,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
    FROM     bill_test1 b
    WHERE          CONNECT_BY_ROOT b.parent_part     = 'ABC-1'
    CONNECT BY     parent_part     = PRIOR child_part
    ORDER SIBLINGS BY     b.line_nbr
    ;
    

    I said the query you posted does not require a subquery. It also does not require double, so I guess that what you posted is a simplification of what you are really doing, and that could have a subquery. In particular, if you want to GROUP BY part_nbr, you need the subquery. We can use CONNECT_BY_ROOT expression in the WHERE clause (or, come to think of it, use a START WITH clause instead WHERE), but, for some reason, we cannot use CONNECT_BY_ROOT in a clause GROUP BY; We need to calculate CONNECT_BY_ROOT in a subquery, give it a name (like part_nbr) and Super GROUP OF this column in a query.

    This requires that there is that one node root. ORDER OF brothers and SŒURS means just that: children of a common parent will appear in the order, but the root nodes, which have no parents, may not be in order.

    Here's what I meant by using START WITH place WHERE:

    SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
    ,     b.parent_part
    ,     b.child_part
    --,     SYS_CONNECT_BY_PATH(b.line_nbr,' ')                    AS seq
    FROM     bill_test1 b
    START WITH     b.parent_part     = 'ABC-1'
    CONNECT BY     parent_part     = PRIOR child_part
    ORDER SIBLINGS BY     b.line_nbr
    ;
    

    This should be much more effective, because it reduces the results before waste you your time by getting their descendants.
    With the help of a clause START WITH here is analogous to me sending you an email, saying "come to a meeting one my office at 03:00."
    By using a WHERE clause here is similar by sending me an e-mail to all members of society, saying: "come to a meeting one my office at 3:00" and then, as people get here, tell everyone except you could go back.

    Brothers and SŒURS ORDER BY was introduced in Oracle 9.

    Published by: Frank Kulash, December 9, 2010 14:39
    Added version with the START WITH clause

  • Need help with rewrite of a query

    Hi friends,

    PFB the query and the result. Please ignore where the conditions, they are only about 50% accurate.

    SELECT XMLELEMENT ( 'majorLine' XMLATTRIBUTES ( ) d. ) line_id AS "Row Id" ),

    xmlforest (d. ) ordered_item as "itemName" , 

    d . ordered_quantity as 'quantity' ),

    (SELECT XMLAGG (XMLELEMENT ()"Service" XMLATTRIBUTES (e. ))) line_id AS Service ),

    ( ) SELECT XMLAGG (XMLELEMENT ( "ServiceName" ))

    XMLATTRIBUTES (of. ) ordered_item AS "ItemName" ),

    xmlforest (of. ) ordered_item as "itemName" , 

    de . ordered_quantity as 'quantity' )))

    DE oe_order_lines_all of

    de . line_id = e. line_id et de . link_to_line_id is null ))) 

    DE oe_order_lines_all e

    e. line_id = 143424538 ),

    (SELECT XMLAGG (XMLELEMENT ()"minorLine" XMLATTRIBUTES (e. ))) line_id AS minorLine ),

    ( ) SELECT XMLAGG (XMLELEMENT ( "itemName" ))

    XMLATTRIBUTES (of. ) ordered_item AS "ItemName" ),

    xmlforest (of. ) ordered_item as "itemName" , 

    de . ordered_quantity as 'quantity' )))

    DE oe_order_lines_all of

    de . line_id = e. line_id )))

    DE oe_order_lines_all e

    ( e. line_id = 143424538 ), (SELECT XMLAGG (XMLELEMENT ()"service" XMLATTRIBUTES (e. ))) line_id AS Service ),

    ( ) SELECT XMLAGG (XMLELEMENT ( "serviceName" ))

    XMLATTRIBUTES (of. ) ordered_item AS "itemName" ),

    xmlforest (of. ) ordered_item as "itemName" , 

    de . ordered_quantity as 'quantity' )))

    DE oe_order_lines_all of

    de . line_id = e. line_id et de . link_to_line_id is null ))) 

    DE oe_order_lines_all e

    ( e. line_id = 143424538 ( )

    ( ) YOU "dept_list"

    DE oe_order_lines_all d d . line_id = 143424538 ;



    The output is:


    < majorLine Line Id='143424538'>

    < itemName > 15454-TCC3-K9 = </ itemName >

    < quantity > 10 < / quantity >

    < Service SERVICE='143424538'>

    < ServiceName ItemName'15454-TCC3-K9 ='=>

    < itemName > 15454-TCC3-K9 = </ itemName >

    < quantity > 10 < / quantity >

    </ ServiceName >

    </ Service >

    < minorLine MINORLINE='143424538'>

    < itemName ItemName'15454-TCC3-K9 ='=>

    < itemName > 15454-TCC3-K9 = </ itemName >

    < quantity > 10 < / quantity >

    </ itemName >

    </ minorLine >

    < service SERVICE='143424538'>

    < serviceName itemName'15454-TCC3-K9 ='=>

    < itemName > 15454-TCC3-K9 = </ itemName >

    < quantity > 10 < / quantity >

    </ serviceName >

    </ service >

    </ majorLine >

    But the production expected as below

    < majorLine Line Id="143">

    < itemName > 15454-K = </ itemName >

    < quantity > 10 < / quantity >

    < Service >

    < lineId >143424538 < / lineId >

    < itemName > 15454-9 = </ itemName >

    < quantity > 10 < / quantity >

    </ Service >

    < minorLine MINORLINE='143424538'>

    < itemName > 1549 = </ itemName >

    < quantity > 10 < / quantity >

    </ minorLine >

    < service >

    < lineId >143424538 < / lineId >  

    < itemName > 159= </ itemName >

    < quantity > 10 < / quantity >

    </ service >

    </ majorLine >



    So the exact structure of XML output will be like that. In the example above, I didn't add the service of minors and several minor lines.

    I need to change the code above in the format below.



    < majorLine = "123456" LineID >-> there will be only one line of Major

    < itemNamme > MajorLineItem < / itemName >

    < quantity > 2 < / quantity >

    < service > -> there may be more than one service or no service of this major axis

    < > < lineId > 123456 lineId

    < itemNamme > serviceOfmajor < / itemName >

    < quantity > 2 < / quantity >

    < / service >

    < minorLine LineID '456789' = > -> there are several minor this major line lines

    < itemNamme > first_MinorlineItem < / itemName >

    < quantity > 7 < / quantity >

    < service >-> there may be more than one or NONE of the lines of service for one minor line

    < > < lineId > 11212 lineId

    < itemNamme > First_serivceOfMinor < / itemName >

    < quantity > 2 < / quantity >      

    < / service >

    < service >-> it may be more than one service lines for a line of minor

    < > 1347657 < lineId > lineId

    < itemNamme > second_serivceOfMinor < / itemName >

    < quantity > 2 < / quantity >      

    < / service >

    < minorLine LineID = "477838" > -> there are several minor this major line lines

    < itemNamme > second_MinorlineItem < / itemName >

    < quantity > 3 < / quantity >

    < / majorLine >



    Please help me to re - write the code. I used the approach of DOM node, its very long, I'm trying to replace it. Help, please. Let me know if you have any questions.


    Thank you and best regards,

    Arun Thomas T





    Not a Constructive Question.

  • [10 g/8i] Need help with setting up a query

    I have a query that takes about 5 minutes to run, and if there is a way to make it faster, I would like to know. It is not a huge problem, but I get to sleep while waiting for it to end. =)

    Here are the results of the explain plan command and the extra stuff generated by autotrace...
    SQL> show parameter optimizer
    
    NAME                                 TYPE        VALUE
    ------------------------------------ ----------- ------------------------------
    optimizer_dynamic_sampling           integer     2
    optimizer_features_enable            string      10.2.0.1
    optimizer_index_caching              integer     0
    optimizer_index_cost_adj             integer     100
    optimizer_mode                       string      ALL_ROWS
    optimizer_secure_view_merging        boolean     TRUE
    SQL> 
    SQL> show parameter db_file_multi
    
    NAME                                 TYPE        VALUE
    ------------------------------------ ----------- ------------------------------
    db_file_multiblock_read_count        integer     128
    SQL> 
    SQL> show parameter db_block_size
    
    NAME                                 TYPE        VALUE
    ------------------------------------ ----------- ------------------------------
    db_block_size                        integer     8192
    SQL> 
    SQL> show parameter cursor_sharing
    
    NAME                                 TYPE        VALUE
    ------------------------------------ ----------- ------------------------------
    cursor_sharing                       string      EXACT
    SQL> 
    SQL> column sname format a20
    SQL> column pname format a20
    SQL> column pval2 format a20
    SQL> 
    SQL> select
      2           sname
      3         , pname
      4         , pval1
      5         , pval2
      6  from
      7         sys.aux_stats$;
    
    SNAME                PNAME                      PVAL1 PVAL2
    -------------------- -------------------- ----------- --------------------
    SYSSTATS_INFO        STATUS                           COMPLETED
    SYSSTATS_INFO        DSTART                           02-07-2006 22:54
    SYSSTATS_INFO        DSTOP                            02-07-2006 22:54
    SYSSTATS_INFO        FLAGS                      1.000
    SYSSTATS_MAIN        CPUSPEEDNW               500.790
    SYSSTATS_MAIN        IOSEEKTIM                 10.000
    SYSSTATS_MAIN        IOTFRSPEED             4,096.000
    SYSSTATS_MAIN        SREADTIM
    SYSSTATS_MAIN        MREADTIM
    SYSSTATS_MAIN        CPUSPEED
    SYSSTATS_MAIN        MBRC
    SYSSTATS_MAIN        MAXTHR
    SYSSTATS_MAIN        SLAVETHR
    
    13 rows selected.
    
    Elapsed: 00:00:00.03
    SQL> explain plan into plan_table for
      2  SELECT     CONNECT_BY_ROOT b.parent_part                         AS part_nbr
      3       ,     b.parent_part
      4       ,     b.child_part
      5       ,     eval_number ('1' || SYS_CONNECT_BY_PATH (b.qty_per, '*'))     AS qty
      6       FROM     (
      7            SELECT     doc_nbr          AS parent_part
      8            ,     comp_part     AS child_part
      9            ,     line_nbr
     10            ,     qty_per
     11            FROM     bill@DB8I
     12            WHERE     lst_code     IN ('G','M')
     13            AND     begn_eff     <= SYSDATE
     14            AND     end_eff          > SYSDATE
     15            AND      component_type     = 'R'
     16            AND     doc_type     = 'BILL'
     17            AND     status          = 'RL'
     18            ) b
     19       ,     part@DB8I p
     20       ,     dual
     21       WHERE     b.child_part     = p.part_nbr
     22       START WITH     b.parent_part          = 'MYPARTNBR'
     23       CONNECT BY     b.parent_part          = PRIOR b.child_part
     24       AND          PRIOR p.part_type     = 'M'
     25  ;
    
    Explained.
    
    Elapsed: 00:00:00.23
    SQL> select * from table(dbms_xplan.display);
    
    PLAN_TABLE_OUTPUT
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Plan hash value: 2565617462
    
    --------------------------------------------------------------------------------------------------
    | Id  | Operation                 | Name | Rows  | Bytes | Cost (%CPU)| Time     | Inst   |IN-OUT|
    --------------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT          |      |     1 |   299 |   519  (14)| 00:00:07 |        |      |
    |*  1 |  CONNECT BY WITH FILTERING|      |       |       |            |          |        |      |
    |*  2 |   FILTER                  |      |       |       |            |          |        |      |
    |   3 |    COUNT                  |      |       |       |            |          |        |      |
    |   4 |     NESTED LOOPS          |      |     1 |   299 |   519  (14)| 00:00:07 |        |      |
    |   5 |      NESTED LOOPS         |      |     1 |   217 |   517  (14)| 00:00:07 |        |      |
    |   6 |       FAST DUAL           |      |     1 |       |     2   (0)| 00:00:01 |        |      |
    |   7 |       REMOTE              | BILL |     1 |   217 |   515  (14)| 00:00:07 |  DB8I  | R->S |
    |   8 |      REMOTE               | PART |     1 |    82 |     2   (0)| 00:00:01 |  DB8I  | R->S |
    |*  9 |   HASH JOIN               |      |       |       |            |          |        |      |
    |  10 |    CONNECT BY PUMP        |      |       |       |            |          |        |      |
    |  11 |    COUNT                  |      |       |       |            |          |        |      |
    |  12 |     NESTED LOOPS          |      |     1 |   299 |   519  (14)| 00:00:07 |        |      |
    |  13 |      NESTED LOOPS         |      |     1 |   217 |   517  (14)| 00:00:07 |        |      |
    |  14 |       FAST DUAL           |      |     1 |       |     2   (0)| 00:00:01 |        |      |
    |  15 |       REMOTE              | BILL |     1 |   217 |   515  (14)| 00:00:07 |  DB8I  | R->S |
    |  16 |      REMOTE               | PART |     1 |    82 |     2   (0)| 00:00:01 |  DB8I  | R->S |
    |  17 |   COUNT                   |      |       |       |            |          |        |      |
    |  18 |    NESTED LOOPS           |      |     1 |   299 |   519  (14)| 00:00:07 |        |      |
    |  19 |     NESTED LOOPS          |      |     1 |   217 |   517  (14)| 00:00:07 |        |      |
    |  20 |      FAST DUAL            |      |     1 |       |     2   (0)| 00:00:01 |        |      |
    |  21 |      REMOTE               | BILL |     1 |   217 |   515  (14)| 00:00:07 |  DB8I  | R->S |
    |  22 |     REMOTE                | PART |     1 |    82 |     2   (0)| 00:00:01 |  DB8I  | R->S |
    --------------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       1 - filter("DOC_NBR"='MYPARTNBR')
       2 - filter("DOC_NBR"='MYPARTNBR')
       9 - access("DOC_NBR"=NULL AND NULL='M')
    
    Remote SQL Information (identified by operation id):
    ----------------------------------------------------
    
       7 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
           R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
           "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
           "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
       8 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
           'DB8I ' )
    
      15 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
            R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
            "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
            "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
      16 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
            'DB8I ' )
    
      21 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
            R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
            "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
            "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
      22 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
            'DB8I ' )
    
    
    ...
    ...
    ...
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       1 - filter("DOC_NBR"='MYPARTNBR')
       2 - filter("DOC_NBR"='MYPARTNBR')
       9 - access("DOC_NBR"=NULL AND NULL='M')
    
    Remote SQL Information (identified by operation id):
    ----------------------------------------------------
    
       7 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
           R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
           "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
           "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
       8 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
           'DB8I ' )
    
      15 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
            R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
            "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
            "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
      16 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
            'DB8I ' )
    
      21 - SELECT "DOC_NBR","BEGN_EFF","END_EFF","LST_CODE","COMP_PART_NBR","QTY_PE
            R","COMPONENT_TYPE","DOC_TYPE","STATUS" FROM "BILL" "BILL" WHERE "COMPONENT_TYPE"='R' AND
            "DOC_TYPE"='BILL' AND "STATUS"='RL' AND ("LST_CODE"='G' OR "LST_CODE"='M') AND
            "END_EFF">:1 AND "BEGN_EFF"<=:2 (accessing 'DB8I ' )
    
      22 - SELECT "PART_NBR","PART_TYPE" FROM "PART" "P" WHERE :1="PART_NBR" (accessing
            'DB8I ' )
    
    
    
    Statistics
    ----------------------------------------------------------
            381  recursive calls
              1  db block gets
              0  consistent gets
              0  physical reads
            304  redo size
          15558  bytes sent via SQL*Net to client
            417  bytes received via SQL*Net from client
              5  SQL*Net roundtrips to/from client
              6  sorts (memory)
              0  sorts (disk)
            379  rows processed
    
    SQL> disconnect
    Disconnected from Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
    I also have the tkprof output, but let's start with that. I have absolutely no idea where to even start looking for something to improve.

    Performance would be much better if the whole query would be executed on the remote side, but the query uses the local function eval_number as well as parts of the query are executed on the remote side and results are brought alongside local and then only filtering is performed. Try the following:

    SELECT  part_nbr,
            parent_part,
            child_part,
            eval_number ('1' || path) qty
      FROM  (
             SELECT  CONNECT_BY_ROOT b.parent_part part_nbr,
                     b.parent_part,
                     b.child_part,
                     SYS_CONNECT_BY_PATH(b.qty_per, '*') path
               FROM  (
                      SELECT  doc_nbr parent_part,
                              comp_part child_part,
                              line_nbr
                              qty_per
                        FROM  bill@DB8I
                        WHERE lst_code IN ('G','M')
                          AND begn_eff <= SYSDATE
                          AND end_eff  > SYSDATE
                          AND component_type = 'R'
                          AND doc_type = 'BILL'
                          AND status  = 'RL'
                     ) b,
                     part@DB8I p
               WHERE b.child_part = p.part_nbr
               START WITH b.parent_part  = 'MYPARTNBR'
               CONNECT BY b.parent_part  = PRIOR b.child_part
                   AND PRIOR p.part_type = 'M'
            )
    /
    

    SY.

  • [8i] need help with hierarchical (connection by) query

    First of all, I work in 8i.

    My problem is, I get the error ORA-01437 message: cannot have join with CONNECT BY.
    And the reason why I get this error because one of the criteria that I use to cut a few branches with is in another table... Is anyway to circumvent this? I tried a view online (but got the same error). I thought to use the connection by query views online and filtering off the coast of what I don't want in this way, but I don't know how to filter an entire branch...

    Simplified data examples:
    CREATE TABLE     bom_test
    (     parent          CHAR(25)
    ,     component     CHAR(25)
    ,     qty_per          NUMBER(9,5)
    );
    
    INSERT INTO     bom_test
    VALUES     ('ABC-1','101-34',10);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','A-109-347',2);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','ABC-100G',1);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','1A247G01',2);
    INSERT INTO     bom_test
    VALUES     ('ABC-100G','70052',18);
    INSERT INTO     bom_test
    VALUES     ('ABC-100G','M9532-278',5);
    INSERT INTO     bom_test
    VALUES     ('1A247G01','X525-101',2);
    INSERT INTO     bom_test
    VALUES     ('1A247G01','1062-324',2);
    INSERT INTO     bom_test
    VALUES     ('X525-101','R245-9010',2);
    
    CREATE TABLE     part_test
    (     part_nbr     CHAR(25)
    ,     part_type     CHAR(1)
    );
    
    INSERT INTO     part_test
    VALUES     ('ABC-1','M');
    INSERT INTO     part_test
    VALUES     ('101-34','P');
    INSERT INTO     part_test
    VALUES     ('A-109-347','P');
    INSERT INTO     part_test
    VALUES     ('ABC-100G','M');
    INSERT INTO     part_test
    VALUES     ('1A247G01','P');
    INSERT INTO     part_test
    VALUES     ('70052','P');
    INSERT INTO     part_test
    VALUES     ('M9532-278','P');
    INSERT INTO     part_test
    VALUES     ('X525-101','M');
    INSERT INTO     part_test
    VALUES     ('1062-324','P');
    INSERT INTO     part_test
    VALUES     ('R245-9010','P');
    It's the questioning of base (with no pruning of branches):
    SELECT     LEVEL
    ,     b.component
    ,     b.parent
    ,     b.qty_per
    FROM     bom_test b
    START WITH          b.parent     = 'ABC-1'
    CONNECT BY PRIOR     b.component     = b.parent
    The above query results:
          LEVEL COMPONENT                 PARENT                        QTY_PER
    ----------- ------------------------- ------------------------- -----------
          1.000 101-34                    ABC-1                          10.000
          1.000 A-109-347                 ABC-1                           2.000
          1.000 ABC-100G                  ABC-1                           1.000
          2.000 70052                     ABC-100G                       18.000
          2.000 M9532-278                 ABC-100G                        5.000
          1.000 1A247G01                  ABC-1                           2.000
          2.000 X525-101                  1A247G01                        2.000
          3.000 R245-9010                 X525-101                        2.000
          2.000 1062-324                  1A247G01                        2.000
    
    9 rows selected.
    .. .but I want to only the branches (children, grandchildren, etc.) the type of part of'm '.
    for example:
          LEVEL COMPONENT                 PARENT                        QTY_PER
    ----------- ------------------------- ------------------------- -----------
          1.000 101-34                    ABC-1                          10.000
          1.000 A-109-347                 ABC-1                           2.000
          1.000 ABC-100G                  ABC-1                           1.000
          2.000 70052                     ABC-100G                       18.000
          2.000 M9532-278                 ABC-100G                        5.000
          1.000 1A247G01                  ABC-1                           2.000
    Any suggestions?

    Hello

    Difficult problem!

    Sorry for the false leads I posted last night.
    In Oracle 8.1, you can CONNECT BY first of all, in a view online and then to join her, but you can't do the reverse.
    We can change the 3 query to get the desired results by replacing the external CONNECTION BY a series of analytical functions to locate all ancestors and finally SELECT a line only if all the ancestors had part_type = am'.

    It's not pretty, but it works:

    SELECT       component, parent, qty_per
    --,       r_num, lvl
    --,       SUM (ancestor_ok)
    FROM        (       -- Begin in-line view to calculate ancestor_ok
           SELECT       m.*
           ,       CASE
                      WHEN c_num < lvl
                          THEN  LAG ( part_ok
                                      , r_num - NVL ( a_pos
                                                          , 0
                                          )
                                ) OVER ( PARTITION BY  c_num
                                                 ORDER BY          r_num
                                         )
                  END                    AS ancestor_ok
              FROM       (     -- Begin in-line view of 'M' parts in hierarchy
                      SELECT     h.component
                   ,     h.parent
                   ,     h.qty_per
                   ,     h.r_num
                   ,     h.lvl
                   ,     p.part_ok
                   ,     c.c_num
                   ,     MAX ( CASE
                                       WHEN  lvl = c_num
                                   THEN  r_num
                                   ELSE  0
                                    END
                                ) OVER ( PARTITION BY  c_num
                                              ORDER BY      r_num
                                       ROWS BETWEEN  UNBOUNDED PRECEDING
                                              AND        1          PRECEDING
                                   )       AS a_pos
                      FROM     (     -- Begin in-line view h, hierarchy from bom_test
                             SELECT     component
                             ,     parent
                             ,     qty_per
                             ,     ROWNUM          AS r_num
                             ,     LEVEL          AS lvl
                             FROM     bom_test
                             START WITH     parent     = 'ABC-1'
                             CONNECT BY     parent     = PRIOR component
                           ) h     -- End in-line view h, hierarchy from bom_test
                      ,     (      -- Begin in-line view p, to get part+_ok from part_test
                             SELECT  part_nbr
                             ,     CASE
                                        WHEN  part_type = 'M'
                                        THEN  1
                                        ELSE  0
                                  END          AS part_ok
                             FROM    part_test
                           ) p     -- End in-line view p, to get part+_ok from part_test
                      ,     (     -- Begin in-line view c, counter
                             SELECT      ROWNUM           AS c_num
                             FROM      bom_test
                             WHERE      ROWNUM     <= 10     -- Guess at maximum number of levels, or omit
                           ) c     -- End in-line view c, counter
                      WHERE     p.part_nbr     = h.component
                   AND     c.c_num          <= h.lvl
                   ) m     -- End in-line view of 'M' parts in hierarchy
           )       -- End  in-line view to calculate ancestor_ok
    GROUP BY  component, parent, qty_per
    ,       r_num, lvl
    HAVING       lvl = 1
    OR       lvl = 1 + SUM (ancestor_ok)
    ORDER BY  r_num
    ;
    

    On 11 lines from the bottom, I assumed that the maximum depth of any node would be 10. If you do not higher that it should really be, or if you delete that WHEN the clause, then the query still works, it'll just be less effective.

    This works for your sample data and some variations I've tried, including the case where a component has many parents. Sorry, I could not test it very carefully. Try it on some of your actual data, and let me know if there are problems.

    I'll try to post a more detailed explanation later.
    Basically, it works by capturing the results CONNECT BY in subquery h. Each line is identified solely by r_num, giving its place in CONNECT BY results.
    In the subquery m, where most of the work takes place, it calculates the a_pos, the r_num of the ancestor of a node at a given level. That value is used in the LAG later function to see if the ancestor was part_type = am' or not. Only the lines where all the ancestors had part_type = am' are included in the final result set.

    I did have the time to read the messages you and Dev published today. I'll try to do this and get back to you.

    Once more remind the people responsible that the Oracle 8.1 was replaced 9 years ago. Whatever they save by not upgrading is offset by what you have to write and maintain much more complicated code, which in turn runs much, much slower than something on a more recent database.
    The following works in Oracle 10 and I think it would work in Oracle 9, too:

    SELECT     b.component, b.parent, b.qty_per
    FROM     bom_test     b
    JOIN     part_test    p     ON     b.component     = p.part_nbr
    START WITH      b.parent     = 'ABC-1'
    CONNECT BY     b.parent       = PRIOR b.component
         AND     PRIOR p.part_type = 'M'
    ;
    

    It's 7 lines of code instead of about 65 years it takes to do the same in Oracle 8.1.

  • [8i] need help with full outer join combined with a cross join...

    I can't understand how to combine a full outer join with a different type of join... is it possible?

    Here are some create table and insert for examples of database:
    CREATE TABLE     my_tab1
    (     record_id     NUMBER     NOT NULL     
    ,     workstation     VARCHAR2(4)
    ,     my_value     NUMBER
         CONSTRAINT my_tab1_pk PRIMARY KEY (record_id)
    );
    
    INSERT INTO     my_tab1
    VALUES(1,'ABCD',10);
    INSERT INTO     my_tab1
    VALUES(2,'ABCD',15);
    INSERT INTO     my_tab1
    VALUES(3,'ABCD',5);
    INSERT INTO     my_tab1
    VALUES(4,'A123',5);
    INSERT INTO     my_tab1
    VALUES(5,'A123',10);
    INSERT INTO     my_tab1
    VALUES(6,'A123',20);
    INSERT INTO     my_tab1
    VALUES(7,'????',5);
    
    
    CREATE TABLE     my_tab2
    (     workstation     VARCHAR2(4)
    ,     wkstn_name     VARCHAR2(20)
         CONSTRAINT my_tab2_pk PRIMARY KEY (workstation)
    );
    
    INSERT INTO     my_tab2
    VALUES('ABCD','WKSTN 1');
    INSERT INTO     my_tab2
    VALUES('A123','WKSTN 2');
    INSERT INTO     my_tab2
    VALUES('B456','WKSTN 3');
    
    CREATE TABLE     my_tab3
    (     my_nbr1     NUMBER
    ,     my_nbr2     NUMBER
    );
    
    INSERT INTO     my_tab3
    VALUES(1,2);
    INSERT INTO     my_tab3
    VALUES(2,3);
    INSERT INTO     my_tab3
    VALUES(3,4);
    And, the results that I want to get:
    workstation     sum(my_value)     wkstn_name     my_nbr1     my_nbr2
    ---------------------------------------------------------------
    ABCD          30          WKSTN 1          1     2
    ABCD          30          WKSTN 1          2     3
    ABCD          30          WKSTN 1          3     4
    A123          35          WKSTN 2          1     2
    A123          35          WKSTN 2          2     3
    A123          35          WKSTN 2          3     4
    B456          0          WKSTN 3          1     2
    B456          0          WKSTN 3          2     3
    B456          0          WKSTN 3          3     4
    ????          5          NULL          1     2
    ????          5          NULL          2     3
    ????          5          NULL          3     4
    I tried a number of different things, google my problem and no luck yet...
    SELECT     t1.workstation
    ,     SUM(t1.my_value)
    ,     t2.wkstn_name
    ,     t3.my_nbr1
    ,     t3.my_nbr2
    FROM     my_tab1 t1
    ,     my_tab2 t2
    ,     my_tab3 t3
    ...
    So, what I want, it's a full outer join of t1 and t2 on workstation and a cross join of one with the t3. I wonder if I can't find examples of it online because it is not possible...

    Note: I'm stuck dealing with Oracle 8i

    Thank you!!

    Hello

    The query I posted yesterday is a little more complex that it should be.
    My_tab2.workstation is unique, there is no reason to make a separate subquery as mt1. We can join my_tab1 to my_tab2 and get the SUM in a subquery.

    SELECT       foj.workstation
    ,       foj.sum_my_value
    ,       foj.wkstn_name
    ,       mt3.my_nbr1
    ,       mt3.my_nbr2
    FROM       (     -- Begin in-line view foj for full outer join
              SELECT        mt1.workstation
              ,        SUM (mt1.my_value)     AS sum_my_value
              ,        mt2.wkstn_name
              FROM        my_tab1   mt1
              ,        my_tab2   mt2
              WHERE        mt1.workstation     = mt2.workstation (+)
              GROUP BY   mt1.workstation
              ,        mt2.wkstn_name
                            --
                    UNION ALL
                            --
              SELECT      workstation
              ,      0      AS sum_my_value
              ,      wkstn_name
              FROM      my_tab2
              WHERE      workstation     NOT IN (     -- Begin NOT IN sub-query
                                               SELECT      workstation
                                       FROM      my_tab1
                                       WHERE      workstation     IS NOT NULL
                                     )     -- End NOT IN sub-query
           ) foj     -- End in-line view foj for full outer join
    ,       my_tab3  mt3
    ORDER BY  foj.wkstn_name
    ,       foj.workstation
    ,       mt3.my_nbr1
    ,       mt3.my_nbr2
    ;
    

    Thanks for posting the CREATE TABLE and INSERT statements, and very clear expected results!

    user11033437 wrote:
    ... So, what I want, it's a full outer join of t1 and t2 on workstation and a cross join of one with the t3.

    She, exactly!
    The trickiest part is when and how get SUM (my_value). You could address the question of exactly what my_tab3 must be attached to a cross that's exactly what should look like the result set of the full outer join between my_tab1 and my_tab2 to. To do this, take your desired results, remove columns that do not come from the outer join complete and delete duplicate rows. You will get:

    workstation     sum(my_value)     wkstn_name
    -----------     -------------   ----------
    ABCD          30          WKSTN 1
    A123          35          WKSTN 2
    B456          0          WKSTN 3
    ????          5          NULL          
    

    So the heart of the problem is how to get these results of my_tab1 and my_tab2, which is done in the subquery FOJ above.

    I tried to use auto-documenté in my code names. I hope you can understand.
    I could spend hours explaining the different parts of this query more in detail, but I don't know that I would lose some of that time, explain things that you already understand. If you want an explanation of the specific element (s), let me know.

  • Need help with a query result

    Oracle Version: 11.2.0.2.0

    I need assistance with the output of the query. Here is the table.

    With Tbl_Nm as

    (

    Select 'ABC1' SYSTEM_ID, REGION 'US', 'CHI' SUB_REGION 4000 BALANCE, to_date('1-JUN-2012 10:45:00 am', 'dd-mon-yyyy hh:mi:ss am') LAST_UPD_TIME, 'A' FLAG of union double all the

    Select 'PQR2', 'UK', 'LN', 2000, To_Date('1-JUL-2012 10:46:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All

    Select 'ABC1', 'IND","MAMA", 3500, To_Date('1-AUG-2012 11:47:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select "LMN3", "US", "NJ", 2500, To_Date('1-SEP-2012 09:49:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select "PQR2", "UK", "MC", 2600, To_Date('1-OCT-2012 04:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select 'ABC1', 'US', 'NY', 3200, To_Date('1-OCT-2012 06:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All

    Select "LMN3", "UK", "BT", 2400, To_Date('1-NOV-2012 07:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' From Dual

    )

    Select * from tbl_nm

    I need the output below.

    PQR2 UK MC 2600 1 OCTOBER 2012 04:45

    ABC1 US NY 3500 October 1, 2012 06:45

    LMN3 UK BT 2500 November 1, 2012 07:45

    The need the disc according to this system_id flagged as "A". But if the last disc of 'd' then it must show that the amount, but the file should be displayed in 'A '.

    I've tried a few and got stuck. Help, please. Not able to get a balance '.

    This question is a bit similar to needing help with a query result

    With Tbl_Nm as

    (

    Select 'ABC1' System_Id, region 'US', 'CHI' Sub_Region, 4000 balance, To_Date('1-JUN-2012 10:45:00 am', 'dd-mon-yyyy hh:mi:ss am') Last_Upd_Time, 'A' flag of double Union All

    Select 'PQR2', 'UK', 'LN', 2000, To_Date('1-JUL-2012 10:46:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All

    Select 'ABC1', 'IND","MAMA", 3500, To_Date('1-AUG-2012 11:47:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select "LMN3", "US", "NJ", 2500, To_Date('1-SEP-2012 09:49:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select "PQR2", "UK", "MC", 2600, To_Date('1-OCT-2012 04:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), 'A' from dual Union All

    Select 'ABC1', 'US', 'NY', 3200, To_Date('1-OCT-2012 06:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' starting from dual Union All

    Select "LMN3", "UK", "BT", 2400, To_Date('1-NOV-2012 07:45:00 am', 'dd-mon-yyyy hh:mi:ss am'), has ' From Dual

    )

    Select System_Id, region, Sub_Region, Balance, Last_Upd_Time of Tbl_Nm T1

    where t1. Last_Upd_Time = (select max (Last_Upd_Time) in the Tbl_Nm T2 where T1.) SYSTEM_ID = T2. SYSTEM_ID)

    So maybe you'd then

    ORDER BY DECODE(flag,'D',9,1) ASC...

    to get the Ds at the end of the list.

    or

    ORDER BY CASE WHAT flag = has ' (your other filters) AND then 9 or 1 end CSA,...

    HTH

  • Need help with a SQL query

    Hello

    I have a data in table (raj_table) with columns (char11) raj_id, raj_number (varchar2 (15)), raj_format (NUMBER), Primary_ID (identity with the values of the primary key column)

    Primary_ID raj_id Raj_number Raj_format

    1                            raj                 rajvend                      1

    2                            raj                 rajvend                      1

    3                            raj                 rajvendor1                 2

    4                            raj                 rajvendor1                 2

    5                            raj                 rajvendor1                 2

    6                            raj                 rajvendor2                 3

    I used under SQL to get query output as below, but has not achieved the required result:

    Select client_id vendor_number, vendor_format, primary_id, row_number() on sl_no (client_id partition, primary_id, vendor_format order of client_id primary_id, vendor_format, vendor_number, vendor_number)

    from raj_table by sl_no asc

    SL_NO raj_id raj_number raj_format primary_id

    1                   1                   raj              rajvendor                 1

    1                   2                  raj              rajvendor                 1

    2                   3                   raj              rajvendor1                2

    2                   4                   raj              rajvendor1                2

    2                   5                  raj               rajvendor1                2

    3                   6                    raj              rajvendor2                3

    I need help with a SQL query to get the result as above without using the group by clause. I want to bring together the combination of separate line of the three columns (raj_id, raj_number, raj_format) and add a unique serial number for each online game (SL_NO column below). So, above there are 3 unique set of (raj_id, raj_number, raj_format) I can get in a group by clause, but I can not add prmiary_id, SL_NO values if I group by clause. I used the analytical functions like row_number() but no luck. Need solution for this.

    with t as)

    Select 'raj' raj_id, 'rajvend' raj_number, 1 raj_format, 1 primary_id Union double all the

    Select option 2, 'raj', 'rajvend', 1 double Union all

    Select 3, 'raj', 'rajvendor1', 2 double Union all

    Select 4, 'raj', 'rajvendor1', 2 double Union all

    Select 5, 'raj', 'rajvendor1', 2 double Union all

    Select 6, 'raj', 'rajvendor2', 3 double

    )

    Select dense_rank() over (order of raj_id, raj_number, raj_format) sl_no,

    t.*

    t

    order by primary_id

    /

    PRIMARY_ID RAJ RAJ_NUMBER RAJ_FORMAT SL_NO
    ---------- ---------- --- ---------- ----------
    1 1 raj rajvend 1
    1 2 raj rajvend 1
    2 3 raj rajvendor1 2
    2 4 raj rajvendor1 2
    2 5 raj rajvendor1 2
    3 6 raj rajvendor2 3

    6 selected lines.

    SQL >

    SY.

  • Need help with query Cumulative difference

    Hi all

    I need help with a query and my requirement is as below

    {code}

    ROWNOORDERSVALUE

    110900
    211700
    312500
    413400

    {/ code}

    I have need to query which will display the cumulative difference for example I value tell 10000 numbers opening

    now I need for each of the lines of cumulative difference

    {code}

    ROWNO ORDERS DIFF

    1 10 10000 - 900 = 9100

    2 11 9100 - 700 = 8400

    3 12 8400 - 500 = 7900

    4 13 7900 - 400 = 7500

    {/ code}

    WITH commands LIKE (10 SELECT order_id, 900 double UNION ALL val
    11. SELECT, 700 FROM dual UNION ALL
    SELECT 12, 500 FROM dual UNION ALL
    Select 13, 400 double)

    SELECT row_number() over (ORDER BY order_id ASC) AS rowno
    order_id
    sum (val) 10000 - OVER (ORDER BY order_id ASC) AS diff
    orders

    /

    HTH

  • Need help with query between 2 dates

    Hello

    I did not SEE in a long time and need help with a simple query.

    I have a table of DB access with 3 fields, name, date and number

    What I want is to create a query to retrieve all the names between 2 dates

    When I ask the date field, the results are showing in this formats 2013-07-12 00:00:00

    Here's my query

    < cfquery datasource = 'mydb' name = 'test' >

    SELECT name from myTable

    where edate between ' 2011-01-01 00:00:00 ' AND ' 2013-01-01 00:00:00 '

    < / cfquery >

    < cfoutput query = 'test' >

    #name #.

    < / cfoutput >

    What I get is this error

    ODBC = 22005 (assignment error) error code

    [Microsoft] [ODBC Microsoft Access driver] Type mismatch of data in the expression of the criteria.

    Don't know what I'm doing wrong here.

    Please let me know.

    Thank you

    SELECT ename

    FROM MyTable

    WHERE edate BETWEEN

    AND

    #ename #.

  • Need help with PL/SQL query complex

    I need help with a query that need access to data from 3 tables. That's what I did

    I created 3 tables

    CREATE TABLE post_table
    (
    post_id varchar (20),
    datepost DATE,
    KEY (post_id) elementary SCHOOL
    ) ;

    CREATE TABLE topic
    (
    TOPIC_ID varchar (20),
    name varchar (20),
    PRIMARY KEY (topic_id)
    );

    CREATE TABLE blogpost_table
    (
    TOPIC_ID varchar (20),
    post_id varchar (20),
    PRIMARY KEY (topic_id, post_id);
    FOREIGN KEY (topic_id) REFERENCES topic (topic_id) ON DELETE CASCADE,
    FOREIGN KEY (post_id) REFERENCES post_table (post_id) ON DELETE CASCADE
    );


    Now, I inserted a few values in these tables as

    INSERT INTO post_table VALUES ('p1', to_date ('2009-09-14 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p2', to_date ('2009-07-18 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p3', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p4', to_date ('2009-03-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p5', to_date ('2009-07-13 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p6', to_date ('2009-06-12 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p7', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))

    INSERT INTO VALUES subject ("t1", "baseball");
    INSERT INTO category VALUES ('t2', 'football');

    INSERT INTO blogpost_table VALUES ("t1", "p1");
    INSERT INTO blogpost_table VALUES ('t1', 'p3');
    INSERT INTO blogpost_table VALUES ("t1", "p4");
    INSERT INTO blogpost_table VALUES ('t1', 'p5');
    INSERT INTO blogpost_table VALUES ('t2', 'p2');
    INSERT INTO blogpost_table VALUES ('t2', 'p6');
    INSERT INTO blogpost_table VALUES ("t2", "p7");


    I'm launching SQL queries on the table in this topic.

    I want to write a SQL query that returns me the name of a topic (s) and the number of blog_post (s) associated with the topic in descending order of the number of blog posts created in July.

    Can someone please help me to write this query?

    Thank you

    Published by: user11994430 on October 9, 2009 07:24

    Thanks for the test of the configuration!

    SQL>SELECT   t.NAME, COUNT(*)
      2      FROM topic t, blogpost_table b, post_table p
      3     WHERE b.topic_id = t.topic_id
      4       AND p.post_id = b.post_id
      5       AND p.datepost >= DATE '2009-07-01'
      6       AND p.datepost < DATE '2009-08-01'
      7  GROUP BY t.NAME
      8  ORDER BY COUNT(*) desc;
    
    NAME                   COUNT(*)
    -------------------- ----------
    baseball                      2
    soccer                        2
    

    HTH, Urs

Maybe you are looking for