help to connect by query

I have a requirement where I need to find the parent ID, so I use connect by to find the answer, but there is a mistake I'm committed for which I need help

Table structure: -.

CREATE TABLE EMP

(NUMBER OF BOSS,

NUMBER OF EMP,

NUMBER OF TL);

Insert the script: -.


Insert into EMP (BOSS, EMP, TL)

values (1, -1, null);

Insert into EMP (BOSS, EMP, TL)

values (2, 1, 100);

Insert into EMP (BOSS, EMP, TL)

values (3, 1, 101);

Insert into EMP (BOSS, EMP, TL)

values (4, 1, 102);

Insert into EMP (BOSS, EMP, TL)

values (5, -1, null);

Insert into EMP (BOSS, EMP, TL)

values (6, 5, 201);

Insert into EMP (BOSS, EMP, TL)

values (7, 5, 202);

Insert into EMP (BOSS, EMP, TL)

values (226, -1, null);

Insert into EMP (BOSS, EMP, TL)

values (227, 226, null);

Insert into EMP (BOSS, EMP, TL)

values (228, 227, 726);

Insert into EMP (BOSS, EMP, TL)

values (227, 229, 724);

Insert into EMP (BOSS, EMP, TL)

values (230, 227, 725);

commit;

Up to now, what I've tried is

SELECT * FROM EMP

WHERE TL = 725

START WITH EMP = - 1

CONNECT BY THE BOSS BEFORE = EMP;

I expect output is

EMP BOSS TL

______________________________

227 226

Please correct me where exactly I make a mistake

Thank you

DeWang vora

Like this?

SQL> select emp.*, level from emp start with tl = 725 connect by prior emp =  boss;

      BOSS        EMP         TL      LEVEL
---------- ---------- ---------- ----------
       230        227        725          1
       227        226                     2
       226         -1                     3

Tags: Database

Similar Questions

  • [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.

  • I need help to connect my iPhone apps on El Captian Office

    I need help to connect my iPhone apps on El Captian Office

    Without knowing exactly what you're trying to do, this article from Apple can help:

    Continuity allows you to connect your iPhone, iPad, iPod touch and Mac - Apple Support

  • I need help to connect my macbook pro to my TV high definition. I just installed the latest update for el capitan, and now all of a sudden not work there.  I use a hdmi cable that has worked for me before.  Any suggestions?

    I need help to connect my macbook pro to my TV high definition. I just installed the latest update for el capitan, and now all of a sudden not work there.  I use a hdmi cable that has worked for me before.  Any suggestions?

    OS X El Capitan: use your TV as a monitor

  • Need help with writing a query

    Hi all

    Can someone help please write a query for the following scenario

    Data in the table are in the format below

    student_nameSub1sub1_marksSub2sub2_marksSUB3sub3_marks
    JohnMath90Science80lang85

    Need to write a query to get it as

    student_nameObjectbrands of
    JohnMath90
    JohnScience80
    Johnlang85


    Thank you

    I'm looking so unpivoting the mulitple columns option is there. how it will be used

    I certainly learned something new today.

    create table student_marks(
      student_name varchar2(20),
      sub1 varchar2(20),
      sub1_marks number,
      sub2 varchar2(20),
      sub2_marks number,
      sub3 varchar2(20),
      sub3_marks number
    )
    ;
    insert into student_marks values(
      'john',
      'math',
      90,
      'science',
      80,
      'lang',
      85
    )
    ;
    select
      student_name, sub subject, marks
    from student_marks
    unpivot include nulls (
      (sub, marks)
      for subject in (
        (sub1, sub1_marks),
        (sub2, sub2_marks),
        (sub3, sub3_marks)
        )
    )
    ;
    drop table student_marks purge
    ;
    
    table STUDENT_MARKS created.
    1 rows inserted.
    STUDENT_NAME         SUBJECT                   MARKS
    -------------------- -------------------- ----------
    john                 math                         90
    john                 science                      80
    john                 lang                         85 
    
    table STUDENT_MARKS dropped.
    
  • Please help build a sql query

    Hello

    Please help build a sql query


    My Table Test2015 has given below

    Header_id Line_id Ordered_item       

    723887290 199925 MAIN1

    199925 723887291 MAIN2

    199926 723887292 SH-POS-NO-BR POS-INS

    199926 723887293 MAIN2

    199927 723887294 IC-ENV-NON-BR-ENV-PXY

    199927 723887295 MAIN1

    199927 723887297 MAIN2

    199927 723887298 PRCSS SH-FAIRY-ELEC DISTR.

    199927 723887299 SH-FAIRY-SUM PRO-DE-CONS-HOUSE

    I am trying to query my Test2015 table to obtain the records with ordered_item containing 'MAIN1' and 'MAIN2' only. I tried to write a query as below

    SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1', 'MAIN2');

    But it gives me all the data with the MAIN2 records found but MAIN1 is absent, I want to retrieve only records to both 'MAIN1' and 'MAIN2' present for Header_id.

    While the result below shows me header_id - 199926 and 199929 that he should assume back. I want to fetch documents only with 'MAIN1' and 'MAIN2' both present.

    Header_id Line_id Ordered_item            

    723887290 199925 MAIN1

    199925 723887291 MAIN2

    199926 723887293 MAIN2

    199927 723887295 MAIN1

    199927 723887297 MAIN2

    199929 723887299 MAIN1

    Please suggest.

    Thank you and best regards,

    Prasad.

    Hello

    Try like this...

    SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1") and in header_id (select test2015 WHERE ORDERED_ITEM in ('MAIN2') header_id)

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

  • Help me with SQL Query to retrieve data from a view

    Hello Guru,

    I need help in my sql query.
    I use SQL TeraData.
    I want an Oracle result in the following form-

    Open tickets
    Open months failure / Repair Service s/o improvement request Total general
    2009-01-2 4 4 5 15
    2009-02 1 0 2 3 6
    2009-03 4 1 2 2 9
    Grand Total 7 5 8 10 30


    I wrote the query as where - TIME_PERIOD, RQST_TYPE_DM and DEMAND_SUMMARY_FCT are the points of view and I extract the data from the views only.

    Select NVL (CA. TIME_PERIOD. PERIOD_CD, 'Total') THAT year.
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC Like '% of Break' THEN 1 END) as BreakFix
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC as 'N/a', 1 END) by n/a
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC as 'Improvement' THEN 1 END) accessories
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC Like '% Service' THEN 1 END) as ServiceRequests
    COUNT (CA. RQST_TYPE_DM. RQSTTYP_DESC) AS grand_total
    FROM CA. TIME_PERIOD, CA. RQST_TYPE_DM, CA. DEMAND_SUMMARY_FCT
    WHERE (CA. DEMAND_SUMMARY_FCT. RQSTTYP_ID = CA. RQST_TYPE_DM. RQSTTYP_ID)
    AND (CASE
    WHEN CA. DEMAND_SUMMARY_FCT. MONTH_ID = CA. TIME_PERIOD. PERIOD_ID, 1
    WHEN {fn concat ({fn concat (SUBSTR (CA. TIME_PERIOD. {(PERIOD_CD, 3, 4),'-')}, SUBSTR (CA. TIME_PERIOD. PERIOD_CD, 7, 2))} BETWEEN ' 2009-01' AND ' 2009-03' THEN 1
    WHEN CA. DEMAND_SUMMARY_FCT. RQSTTYP_ID = '1' then 1
    END) = 1
    GROUP BY ROLLUP (CA. TIME_PERIOD. PERIOD_CD)

    After executing the query, I get the following error:
    3076: syntax Error: Data Type 'Time' does not match a defined Type name.
    :( Kindly help me with this and let me know where I'm wrong... Please.

    Messages indicates something wrong with your data... It would seem that the data does not match your format mask.

    Thus, the data or the format mask.

  • Help with making SQL query references to column aliases in the Case statement

    I need help with a sql query that I'm trying. I can go about it the wrong way, but I would be grateful if I could get any suggestions on possible solutions. This is my query:


    SELECT DISTINCT spriden_pidm, spriden_id id, spriden_last_name | ',' | spriden_first_name name,

    CASE
    WHEN rcresar_comm_code_01 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_01
    WHEN rcresar_comm_code_02 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_02
    WHEN rcresar_comm_code_03 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_03
    WHEN rcresar_comm_code_04 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_04
    WHEN rcresar_comm_code_05 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_05
    WHEN rcresar_comm_code_06 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_06
    WHEN rcresar_comm_code_07 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_07
    WHEN rcresar_comm_code_08 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_08
    WHEN rcresar_comm_code_09 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_09
    WHEN rcresar_comm_code_10 IN ('268 ', '269', ' 270') THEN rcresar_comm_code_10
    END acg_elig_comm_code

    CASE
    WHEN acg_elig_comm_code = ' 268' THEN 'rigorous HS course. "
    WHEN acg_elig_comm_code = '269' THEN ' 2 or several AP or IB"
    WHEN acg_elig_comm_code = '270' THEN 'NOC as possible ".
    END comm_code_description

    OF spriden, rcresar, rcrapp1

    WHERE (rcresar_comm_code_01 IN ('268 ', '269', ' 270')

    OR rcresar_comm_code_02 ('268 ', '269', ' 270')

    OR rcresar_comm_code_03 ('268 ', '269', ' 270')

    OR rcresar_comm_code_04 ('268 ', '269', ' 270')

    OR rcresar_comm_code_05 ('268 ', '269', ' 270')

    OR rcresar_comm_code_06 ('268 ', '269', ' 270')

    OR rcresar_comm_code_07 ('268 ', '269', ' 270')

    OR rcresar_comm_code_08 ('268 ', '269', ' 270')

    OR rcresar_comm_code_09 ('268 ', '269', ' 270')

    OR rcresar_comm_code_10 ('268 ', '269', ' 270'))


    Rcresar_aidy_code = & aidy_code

    AND rcrapp1_aidy_code = rcresar_aidy_code

    AND rcrapp1_curr_rec_ind = 'Y '.

    AND rcrapp1_seq_no = rcresar_seq_no


    AND spriden_pidm = rcresar_pidm

    AND rcrapp1_pidm = rcresar_pidm


    AND spriden_change_ind IS NULL

    ORDER BY name


    The second case statement is where I don't know exactly what it takes to get what I want.

    Output should be like:
    spriden_pidm name ID acg_elig_comm_code comm_code_description
    «0000000000', ' 1111111111 ","John Doe","268", «rigorous HS race"»

    If I take the second case statement it works great except that I do not have my comm_code description column. My question is how can I use my first statement value box to determine this column? I think that I need a case statement as I have, but I don't know how to reference the value of acg_elig_comm_code. Any help would be greatly appreciated. Thank you.

    Published by: blackhole82 on January 20, 2009 09:20

    Hello

    You cannot use the alias column in the query, even where it is set (except in the ORDER BY clause).
    You can set the alias in a subquery and then use it in a great query, like this:

    WITH  sub_q  AS
    (
        SELECT DISTINCT spriden_pidm,spriden_id id, spriden_last_name||', '||spriden_first_name name,
            CASE
                WHEN rcresar_comm_code_01 IN ('268','269','270') THEN rcresar_comm_code_01
                WHEN rcresar_comm_code_02 IN ('268','269','270') THEN rcresar_comm_code_02
                WHEN rcresar_comm_code_03 IN ('268','269','270') THEN rcresar_comm_code_03
                WHEN rcresar_comm_code_04 IN ('268','269','270') THEN rcresar_comm_code_04
                WHEN rcresar_comm_code_05 IN ('268','269','270') THEN rcresar_comm_code_05
                WHEN rcresar_comm_code_06 IN ('268','269','270') THEN rcresar_comm_code_06
                WHEN rcresar_comm_code_07 IN ('268','269','270') THEN rcresar_comm_code_07
                WHEN rcresar_comm_code_08 IN ('268','269','270') THEN rcresar_comm_code_08
                WHEN rcresar_comm_code_09 IN ('268','269','270') THEN rcresar_comm_code_09
                WHEN rcresar_comm_code_10 IN ('268','269','270') THEN rcresar_comm_code_10
            END acg_elig_comm_code   -- Originally posted with , here (error)
        FROM spriden, rcresar, rcrapp1
        WHERE (rcresar_comm_code_01 IN ('268','269','270')
                OR rcresar_comm_code_02 IN ('268','269','270')
                OR rcresar_comm_code_03 IN ('268','269','270')
                OR rcresar_comm_code_04 IN ('268','269','270')
                OR rcresar_comm_code_05 IN ('268','269','270')
                OR rcresar_comm_code_06 IN ('268','269','270')
                OR rcresar_comm_code_07 IN ('268','269','270')
                OR rcresar_comm_code_08 IN ('268','269','270')
                OR rcresar_comm_code_09 IN ('268','269','270')
                OR rcresar_comm_code_10 IN ('268','269','270'))
        AND rcresar_aidy_code = &aidy_code
        AND rcrapp1_aidy_code = rcresar_aidy_code
        AND rcrapp1_curr_rec_ind = 'Y'
        AND rcrapp1_seq_no = rcresar_seq_no
        AND spriden_pidm = rcresar_pidm
        AND rcrapp1_pidm = rcresar_pidm
        AND spriden_change_ind IS NULL
    )
    SELECT    sub_q.*,
              CASE
                  WHEN acg_elig_comm_code = '268' THEN 'Rigorous HS course'
                  WHEN acg_elig_comm_code = '269' THEN '2 or more AP or IB'
                  WHEN acg_elig_comm_code = '270' THEN 'ACG possible'
              END comm_code_description
    FROM      sub_q
    ORDER BY  name
    

    Furthermore, you might think to rearrange your table, so that you do not have 10 columns (rcresar_comm_code_01, rcresar_comm_code_02,...) that essentially do the same thing. The usual way to handle this kind of one-to-many relationship is to have all rcresar_comm_codes in a separate table, one per line, with a pointer to the table where you have them now.

    Published by: Frank Kulash, January 20, 2009 11:35
    Syntax error has been corrected

  • SQL query help (we connect by clause level)

    Hi all
    I have this application developed with data with the clause.
     With dat As
    (
      select '@AAA @SSS @DDD' col1 from dual union all
      select '@ZZZ @XXX @TTT @RRR @ZZA' col1 from dual 
    )
    Select regexp_substr( col1 , '[^@][A-Z]+',1,level) Show from dat
    connect by level  <= regexp_count(col1, '@');
    Output current: -.
    SHOW
    -----------------------
    AAA
    SSS
    DDD
    RRR
    ZZA
    TTT
    RRR
    ZZA
    XXX
    DDD
    RRR
    
    SHOW
    -----------------------
    ZZA
    TTT
    RRR
    ZZA
    . . .
    . . .
    1st row comes very well, but the next line data copy. And the number of total records = 30. I tried with some, but not worked.
    Expected results: -.
    SHOW
    -----------------------
    AAA
    SSS
    DDD
    ZZZ 
    XXX 
    TTT 
    RRR 
    ZZA
    I need some changes on my request and I am not able to see that. So anyone can add to that or can also provide a different solution also.

    Thank you!
    Ashutosh

    Thanks for providing the loan to the use of query. :)

    Here's a solution :-(tested on 10 g, do not have 11 g at hand)

    For 11g, just use regexp_count instead of functions of the length.

    With dat As
    (
      select '@AAA @SSS @DDD' col from dual union all
      select '@ZZZ @XXX @TTT @RRR @ZZA' col1 from dual
    )
    Select regexp_substr( col, '[^@][A-Z]+',1,level) Show from dat
    connect by nocycle level  <= length(col) - length(translate(col, 'A@', 'A'))
           and col = prior col
           and prior sys_guid() is not null;
    
    SHOW
    ------------------------
    AAA
    SSS
    DDD
    ZZZ
    XXX
    TTT
    RRR
    ZZA                      
    
     8 rows selected
    
  • Help of the SQL query.

    Hello

    It's my first table REPORT

    report as)
    Select 'vendor_1' vendor, to_date('1/1/2012','DD/MM/YYYY') supply_date, "customer_1" as a customer, "item_1" like item1, 110 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/3/2012','MM/DD/YYYY') supply_date, "customer_1" as a customer, "item_1" like item1, 120 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/3/2012','MM/DD/YYYY') supply_date, "customer_1" as a customer, "item_1" like item1, 130 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/4/2012','MM/DD/YYYY') supply_date, "customer_1" as a customer, "item_1" like item1, 140 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/10/2012','MM/DD/YYYY') supply_date, "customer_1" as a customer, "item_1" element, 200as cost of double union all
    Select 'vendor_1' vendor, to_date('1/23/2012','MM/DD/YYYY') supply_date, "customer_1" as a customer, "item_1" as point 0 as the cost of dual union all
    Select 'vendor_1' vendor, to_date('1/6/2012','MM/DD/YYYY') supply_date, "customer_2" as a customer, "item_1" like item1, 160 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/7/2012','MM/DD/YYYY') supply_date, "customer_2" as a customer, "item_1" like item1, 170 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/8/2012','MM/DD/YYYY') supply_date, "customer_2" as a customer, "item_1" like item1, 180 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/9/2012','MM/DD/YYYY') supply_date, "customer_2" as a customer, "item_1" like item1, 190 as cost of double union all
    Select 'vendor_1' vendor, to_date('1/20/2012','MM/DD/YYYY') supply_date, "customer_2" as a customer, "item_1" like item1, 300 as cost of double)






    IT'S MY SECOND TABLE: TEMP_WEEK

    WITH temp_week (s)
    SELECT January 1, 2012 to 07/01/2012 ' AS the week of all the double union
    SELECT August 1, 2012 to 14/01/2012 ' AS the week of all the double union
    January 15, 2012 to 21/01/2012 ' AS the week of all the double union
    SELECT January 22, 2012 to 28/01/2012 ' AS the week of all the double union
    (SELECT 29 January 2012 to 31/01/2012 ' WEEK of double)


    To find weekly sales that I wrote query below:

    SELECT week, supplier, customer, SUM (cost)
    (SELECT week, supplier, customer, TOTAL costs (cost)
    FROM (SELECT BOX
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 1 AND 7 MAY
    January 1, 2012 to 07/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 8 AND 14 MAY
    14/01/2012, 1 August 2012'
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 15 AND 21 THEN
    January 15, 2012 to 21/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 22 AND 28 and THEN
    January 22, 2012 to 28/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 29 AND 31 MAY
    29 January 2012 to 31/01/2012 '
    END
    week, supplier, customer, cost
    REPORT)
    GROUP BY week, supplier, customer
    UNION ALL
    SELECT tw.week, vendor, customer or 0
    (SELECT week, supplier, customer, TOTAL costs (cost)
    FROM (SELECT BOX
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 1 AND 7 MAY
    January 1, 2012 to 07/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 8 AND 14 MAY
    14/01/2012, 1 August 2012'
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 15 AND 21 THEN
    January 15, 2012 to 21/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 22 AND 28 and THEN
    January 22, 2012 to 28/01/2012 '
    WHEN TO_NUMBER (TO_CHAR (TRUNC (supply_date), 'DD')) BETWEEN 29 AND 31 MAY
    29 January 2012 to 31/01/2012 '
    END
    week, supplier, customer, cost
    REPORT)
    GROUP BY week, supplier, customer), temp_week tw)
    GROUP BY week, supplier, customer
    ORDER BY supplier, customer, week;


    with above query I get below output:


    with output voltage)
    Select January 1, 2012 to 07/01/2012 ' week, 'vendor_1' as a provider, "customer_1" as a customer, 500 as cost of double union all
    Select August 1, 2012, to 14/01/2012 ' week, 'vendor_1' as a provider, "customer_1" as a customer, 200 as cost of double union all
    Select January 15, 2012 to 21/01/2012 ' week, 'vendor_1' as a provider, "customer_1" as a customer, 0 as the cost of dual union all
    Select January 22, 2012 to 28/01/2012 ' week, 'vendor_1' as a provider, "customer_1" as a customer, 0 as the cost of dual union all
    Select the 29 January 2012 to 31/01/2012 ' week, 'vendor_1' as a provider, "customer_1" as a customer, 0 as the cost of dual union all
    Select January 1, 2012 to 07/01/2012 ' week, 'vendor_1' as a provider, "customer_2" as a customer, 330 as costs of double union all
    Select August 1, 2012, to 14/01/2012 ' week, 'vendor_1' as a provider, "customer_2" as a customer, 370 as cost of double union all
    Select January 15, 2012 to 21/01/2012 ' week, 'vendor_1' as a provider, "customer_2" as a customer, 300 as cost of double union all
    Select January 22, 2012 to 28/01/2012 ' week, 'vendor_1' as a provider, "customer_2" as a customer, 0 as the cost of dual union all
    Select the 29 January 2012 to 31/01/2012 ' week, 'vendor_1' as a provider, "customer_2" as a customer, double cost of 0)

    Clearly, I used cross join. But I want to get the same result with another way. I don't want to use cross join and Union

    Please help me in this.

    What you desire can be accomplished using the outer join partitioned.
    The documentation shows an example of [url http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#i2177515] this way to fill the gaps in the data.

    Here's how you can use it in your case:

    SQL> with report as (
      2     select 'vendor_1' as vendor,to_date('1/1/2012','DD/MM/YYYY') supply_date, 'customer_1'as customer,'item_1' as item1, 110 as
    cost from dual union all
      3     select 'vendor_1' as vendor,to_date('1/3/2012','MM/DD/YYYY') supply_date,'customer_1'as customer, 'item_1' as item1,120 as c
    ost from dual union all
      4     select 'vendor_1' as vendor,to_date('1/3/2012','MM/DD/YYYY') supply_date, 'customer_1'as customer, 'item_1' as item1,130 as
    cost from dual union all
      5     select 'vendor_1' as vendor,to_date('1/4/2012','MM/DD/YYYY') supply_date,'customer_1'as customer, 'item_1' as item1,140 as c
    ost from dual union all
      6     select 'vendor_1' as vendor,to_date('1/10/2012','MM/DD/YYYY') supply_date, 'customer_1'as customer, 'item_1' as item ,200as
    cost from dual union all
      7     select 'vendor_1' as vendor,to_date('1/23/2012','MM/DD/YYYY') supply_date, 'customer_1'as customer, 'item_1' as item,0 as co
    st from dual union all
      8     select 'vendor_1' as vendor,to_date('1/6/2012','MM/DD/YYYY') supply_date,'customer_2'as customer, 'item_1' as item1,160 as c
    ost from dual union all
      9     select 'vendor_1' as vendor,to_date('1/7/2012','MM/DD/YYYY') supply_date,'customer_2'as customer, 'item_1' as item1,170 as c
    ost from dual union all
     10     select 'vendor_1' as vendor,to_date('1/8/2012','MM/DD/YYYY') supply_date,'customer_2'as customer, 'item_1' as item1,180 as c
    ost from dual union all
     11     select 'vendor_1' as vendor,to_date('1/9/2012','MM/DD/YYYY') supply_date,'customer_2'as customer,'item_1' as item1,190 as co
    st from dual union all
     12     select 'vendor_1' as vendor,to_date('1/20/2012','MM/DD/YYYY') supply_date,'customer_2'as customer,'item_1' as item1,300 as c
    ost from dual
     13  ), weeks as (
     14     select to_date('1/1/2012','DD/MM/YYYY') + (level-1)*7 week_start
     15          , to_date('1/1/2012','DD/MM/YYYY') + (level-1)*7 + 6 week_end
     16          , level week_pseudo_id
     17       from dual
     18     connect by level <= 5 /* substitute desired number of weeks */
     19  )
     20  --
     21  -- end-of-test-data
     22  --
     23  select to_char(max(weeks.week_start),'DD/MM/YYYY')
     24         || ' to ' ||
     25         to_char(max(weeks.week_end),'DD/MM/YYYY') week
     26       , vendor
     27       , customer
     28       , nvl(sum(cost),0) cost
     29    from report
     30   partition by (vendor, customer)
     31   right outer join weeks
     32         on weeks.week_start <= report.supply_date
     33         and weeks.week_end >= report.supply_date
     34   group by
     35         vendor
     36       , customer
     37       , week_pseudo_id
     38   order by
     39         vendor
     40       , customer
     41       , week_pseudo_id
     42  /
    
    WEEK                     VENDOR   CUSTOMER         COST
    ------------------------ -------- ---------- ----------
    01/01/2012 to 07/01/2012 vendor_1 customer_1        500
    08/01/2012 to 14/01/2012 vendor_1 customer_1        200
    15/01/2012 to 21/01/2012 vendor_1 customer_1          0
    22/01/2012 to 28/01/2012 vendor_1 customer_1          0
    29/01/2012 to 04/02/2012 vendor_1 customer_1          0
    01/01/2012 to 07/01/2012 vendor_1 customer_2        330
    08/01/2012 to 14/01/2012 vendor_1 customer_2        370
    15/01/2012 to 21/01/2012 vendor_1 customer_2        300
    22/01/2012 to 28/01/2012 vendor_1 customer_2          0
    29/01/2012 to 04/02/2012 vendor_1 customer_2          0
    
    10 rows selected.
    

    I have redesigned weeks of date columns for the join which will probably perform better and can possibly use indexes.
    I assume that you have no time portion in your supply_date data? If you do, then week_end will need to be modified.

  • Stuck trying to sort the data of CONNECTION BY query

    Hello

    I ask the Oracle E-Business nothing menu boards.

    This query:
    /*##############################################################################
    #   MENU TREE WALK EXCLUDING FUNCTIONS
    /*############################################################################*/
    SELECT     LPAD('_', (LEVEL - 1) * 10, '_') || fmev.prompt prompt
             , LEVEL
             , fmev.ENTRY_SEQUENCE
          FROM apps.fnd_menus_vl fmv
             , apps.fnd_menu_entries_vl fmev
         wHERE fmev.menu_id = fmv.menu_id
           AND fmev.prompt IS NOT NULL
    CONNECT BY fmev.menu_id = PRIOR fmev.sub_menu_id      
    START WITH fmv.menu_name = 'CN_SETUP';
    Produces this output:
    PROMPT                                   LEVEL     ENTRY_SEQUENCE
    Flexfields                              1     12
    __________Descriptive Flexfields               2     1
    Financials                              1     11
    __________Currencies and Rates                    2     5
    ____________________Rates                    3     10
    ______________________________Daily               4     5
    ______________________________Historical          4     10
    ______________________________Types               4     15
    ____________________Currency Rates Manager          3     5
    ______________________________Daily Rates          4     5
    ______________________________Historical Rates          4     10
    ______________________________Rate Types          4     15
    ____________________Define                    3     15
    __________GL Calendar                         2     2
    __________GL Period Types                    2     3
    __________GL Open and Close Periods               2     4
    Collections                              1     9
    __________Mappings                         2     1
    __________Runtime Values                    2     2
    External Table Mapping                         1     3
    Classification Rules                         1     4
    System Parameters                         1     1
    Payment Plans                              1     6
    Define Pay Groups                         1     14
    View Compensation Groups                    1     16
    Classification Rules                         1     22
    Credit Type Conversions                         1     21
    Credit Types                              1     20
    Interval Types                              1     19
    External Table Mapping                         1     18
    Define Security Profile                         1     17
    Define Payment Plans                         1     15
    Define Salesforce                         1     13
    Lookups                                   1     10
    Revenue Class                              1     8
    Dimensions                              1     7
    Revenue Class                              1     5
    Tables and Columns                         1     2
    I want to sort by order of fmev.entry.

    However, if I do, I get this result:
    PROMPT                                   LEVEL     ENTRY_SEQUENCE
    System Parameters                         1     1
    __________Descriptive Flexfields               2     1
    __________Mappings                         2     1
    __________Runtime Values                    2     2
    Tables and Columns                         1     2
    __________GL Calendar                         2     2
    External Table Mapping                         1     3
    __________GL Period Types                    2     3
    __________GL Open and Close Periods               2     4
    Classification Rules                         1     4
    ____________________Currency Rates Manager          3     5
    ______________________________Daily Rates          4     5
    ______________________________Daily               4     5
    Revenue Class                              1     5
    __________Currencies and Rates                    2     5
    Payment Plans                              1     6
    Dimensions                              1     7
    Revenue Class                              1     8
    Collections                              1     9
    ______________________________Historical Rates          4     10
    ____________________Rates                    3     10
    ______________________________Historical          4     10
    Lookups                                   1     10
    Financials                              1     11
    Flexfields                              1     12
    Define Salesforce                         1     13
    Define Pay Groups                         1     14
    Define Payment Plans                         1     15
    ______________________________Types               4     15
    ______________________________Rate Types          4     15
    ____________________Define                    3     15
    View Compensation Groups                    1     16
    Define Security Profile                         1     17
    External Table Mapping                         1     18
    Interval Types                              1     19
    Credit Types                              1     20
    Credit Type Conversions                         1     21
    Classification Rules                         1     22
    This kind of work, with the exception where the SQL working tree has a parent/child scenario. Ideally, I would like to get the result to look like this:
    PROMPT                                   LEVEL     ENTRY_SEQUENCE
    System Parameters                         1     1
    Tables and Columns                         1     2
    External Table Mapping                         1     3
    Classification Rules                         1     4
    Revenue Class                              1     5
    Payment Plans                              1     6
    Dimensions                              1     7
    Revenue Class                              1     8
    Collections                              1     9
    __________Mappings                         2     1
    __________Runtime Values                    2     2
    Lookups                                   1     10
    Financials                              1     11
    __________Currencies and Rates                    2     5
    ____________________Rates                    3     10
    ______________________________Daily               4     5
    ______________________________Historical          4     10
    ______________________________Types               4     15
    ____________________Currency Rates Manager          3     5
    ______________________________Daily Rates          4     5
    ______________________________Historical Rates          4     10
    ______________________________Rate Types          4     15
    ____________________Define                    3     15
    __________GL Calendar                         2     2
    __________GL Period Types                    2     3
    __________GL Open and Close Periods               2     4
    Flexfields                              1     12
    __________Descriptive Flexfields               2     1
    Define Salesforce                         1     13
    Define Pay Groups                         1     14
    Define Payment Plans                         1     15
    View Compensation Groups                    1     16
    Define Security Profile                         1     17
    External Table Mapping                         1     18
    Interval Types                              1     19
    Credit Types                              1     20
    Credit Type Conversions                         1     21
    Classification Rules                         1     22
    Where the order-by Nick is like this:

    ORDER BY fmev. ENTRY_SEQUENCE for the lowest level, but where there is a submenu, then include those to the right place!

    My apologies for the fact I can't recreate the data here for use in the trial, but as I am using E-Bus tables, it is not so easy.

    Any advice much appreciated.

    Thank you

    ORDER of brothers and SŒURS BY fmev.entry_sequence

    will help you.

    Roger

  • helps to refine this query

    Feature request: list all cases no, paid amout that took place during 2 exercises for each owner at any time given more column sum separte for each fiscal year

    Question: I don't like my query with repetition (what happens if we need 10 years). Can you help me refine?

    Thank you very much.
    --
    create the table test_case_payment
    (
    case_no number not null,
    owner_no number not null,
    paid_amt number (13.2).
    date of paid_date
    );
    --

    create the table test_case_quota
    (
    case_no number not null,
    limit the number of non-null
    );


    insert into test_case_payment (case_no, owner_no, paid_amt, paid_date)
    -data represent FY 2011,2012,2012,2008,2010
    --
    values (1,810,2700,to_date('10/25/2010','MM/DD/YYYY'));
    values (2,820,350,to_date('07/05/2011','MM/DD/YYYY'));
    values (3,810,900,to_date('01/01/2011','MM/DD/YYYY'));
    values (4,840,100,to_date('04/05/2008','MM/DD/YYYY'));
    values (5,850,20,to_date('07/20/2009','MM/DD/YYYY'));

    Insert into test_case_quota (case_no, limit)
    -paid to the ceiling
    --
    values (1,2);
    values (2,2);
    values (3,1);
    values (4.1);
    values (5.1);
    --
    -query starts here
    --
    with FY1 as
    (
    Select a.case_no, a.owner_no, a.paid_amt, b.limit,
    NVL (Sum (a.paid_amt) more (a.owner_no score), 0) FY1_TOTAL
    test_case_payment a, test_case_quota b
    where
    a.case_no = b.case_no
    and a.paid_date between to_date (7/1 /'|) (EXTRAIT (FROM AN to_date (: FY_BEGIN,' JJ/MM/AAAA '))), ' MM/DD/YYYY') and to_date (06/30 /' |) ((EXCERPT (FROM AN to_date(:FY_BEGIN,'MM/DD/YYYY')) + 1), ' MM/DD/YYYY')
    order of a.owner_no, a.case_no
    ),
    FY2 as
    (
    Select a.case_no, a.owner_no, a.paid_amt, b.limit,
    NVL (Sum (a.paid_amt) more (a.owner_no score), 0) FY2_TOTAL
    test_case_payment a, test_case_quota b
    where
    a.case_no = b.case_no
    and a.paid_date between to_date (7/1 /'|) (EXTRAIT (FROM AN to_date (: FY_BEGIN,' JJ/MM/AAAA ")) + 1), ' MM/DD/YYYY') and to_date (06/30 /' |) ((EXCERPT (FROM AN to_date(:FY_BEGIN,'MM/DD/YYYY')) + 2), ' MM/DD/YYYY')
    order of a.owner_no, a.case_no
    ),
    -tables temporary union 2
    FY_UNION as
    (case_no, owner_no, paid_amt, limit, by selecting
    FY1_TOTAL Y1, Y2 FY1 null
    Union
    Select case_no, owner_no, paid_amt, limit,
    Y1, Y2 FY2 FY2_TOTAL NULL)
    --
    -the main query
    Select case_no, owner_no, paid_amt, limit, Y1, Y2 of FY_UNION
    order of owner_no
    -result
    CASE_NO OWNER_NO PAID_AMT     LIMIT      Y1      Y2 
    1      810     2700          2     -      3600 
    3     810      900           1      -        3600 
    5     850      20           1      20      -
    Published by: wanwan63 on October 30, 2011 11:03
    added the format code to display readable output bettter

    Hello

    Thanks for posting the CREATE TABLE and INSERT.
    Please post instructions that work. Did you mean to add something at the beginning of all the statements that now begin with "VALUES"?
    It seems that there are errors in the application, too.

    Because I can not re - create your tables, I'll show what you can do with tables in the scott schema.
    Let's say you have information about the Department, type of employment, date and salary, like this:

    SELECT       d.dname
    ,       e.job
    ,       e.hiredate
    ,       e.sal
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON   d.deptno     = e.deptno
    ORDER BY  d.dname
    ,            e.job
    ;
    

    Output:

    DNAME          JOB       HIREDATE         SAL
    -------------- --------- --------- ----------
    ACCOUNTING     CLERK     23-JAN-82       1300
    ACCOUNTING     MANAGER   09-JUN-81       2450
    ACCOUNTING     PRESIDENT 17-NOV-81       5000
    RESEARCH       ANALYST   19-APR-87       3000
    RESEARCH       ANALYST   03-DEC-81       3000
    RESEARCH       CLERK     23-MAY-87       1100
    RESEARCH       CLERK     17-DEC-80        800
    RESEARCH       MANAGER   02-APR-81       2975
    SALES          CLERK     03-DEC-81        950
    SALES          MANAGER   01-MAY-81       2850
    SALES          SALESMAN  22-FEB-81       1250
    SALES          SALESMAN  08-SEP-81       1500
    SALES          SALESMAN  20-FEB-81       1600
    SALES          SALESMAN  28-SEP-81       1250
    

    and you want to summarize the data, showing the total salary for all those hired for the 2 exercises (July to June), like this:

    DNAME          JOB         Y1_TOTAL   Y2_TOTAL
    -------------- --------- ---------- ----------
    ACCOUNTING     CLERK              0       1300
    ACCOUNTING     MANAGER         2450          0
    ACCOUNTING     PRESIDENT          0       5000
    RESEARCH       ANALYST            0       3000
    RESEARCH       CLERK            800          0
    RESEARCH       MANAGER         2975          0
    SALES          CLERK              0        950
    SALES          MANAGER         2850          0
    SALES          SALESMAN        2850       2750
    

    Here, Y1_TOTAL means the fiscal year beginning July 1, 1980, and Y2_TOTAL refers to the fiscal year beginning July 1, 1981. If hiredate is not in one of these exercises, the line is ignored.

    The Oracle 9 (and more) you can get these results like this:

    VARIABLE     fy_begin     VARCHAR2 (20)
    EXEC  :fy_begin := '07/01/1980';
    
    WITH     years     AS
    (
         SELECT     LEVEL     AS year_num
         ,     ADD_MONTHS ( TO_DATE (:fy_begin, 'MM/DD/YYYY')
                      , 12 * (LEVEL - 1)
                      )              this_year_begin
         ,     ADD_MONTHS ( TO_DATE (:fy_begin, 'MM/DD/YYYY')
                      , 12 *  LEVEL
                      )              next_year_begin
         FROM    dual
         CONNECT BY     LEVEL <= 2     -- Can be any positive integer
    )
    SELECT    d.dname, e.job
    ,       SUM (CASE WHEN year_num = 1 THEN e.sal ELSE 0 END)     AS y1_total
    ,       SUM (CASE WHEN year_num = 2 THEN e.sal ELSE 0 END)     AS y2_total
    FROM       scott.dept     d
    JOIN       scott.emp     e  ON   d.deptno    = e.deptno
    JOIN       years          y  ON   e.hiredate  >= y.this_year_begin
                      AND     e.hiredate  <  y.next_year_begin
    GROUP BY  d.dname, e.job
    ORDER BY  d.dname, e.job
    ;
    

    From Oracle 11, you can also use the SELECT... Function PIVOT. Whenever you have any questions, please say what version of Oracle you are using.

    If you want more exercise, simply change the CONNECT BY clause and add another expression of the SUM (CASE...) by hand, SELECT clause.

    In the above, query: fy_begin determines when to start exercising.
    In your request, it looked like: fy_begin could be any date in the same year civil and July 1 of the calendar year (regardless of the question whether it was before or after: fy_begin) was the beginning of the year. If this is what you want, then instead of
    : fy_begin above, use
    "07/01 /' | SUBSTR (: fy_begin,-4)

  • need help in building a query

    Hello

    using oracle 11 g.
    I have 2 tables.
    One is tableA which is having all the information of the user and the primary key is the useremailid.
    Another table is tableB is having info in case users so the primary key is caseid and the username is the foreign key.
    And ago created other fields as what has been the case, and as there are other fields.

    Now I'm trying
    to retrieve all users in tableA to tableB monthly, even if they did not create case
    as if tableA has
    userA who created the case in tableB on jan - 10 Feb-10
    UserB who created the case in tableB on feb - 10 mar-10

    So those who want to y
    User - Date added - cases created
    Output of query results
    userA - Jan-10 - 10
    userA - Feb-10-20
    userA Mar - 10 - 0
    UserB - Jan-10 - 0
    UserB - Feb-10-200
    UserB Mar-10 - 90

    create stmts are like this->
    Create table TableA
    (
    Username varchar (120) (PK)
    )

    Create table TableB
    (
    case_id varchar (15), (PK)
    cases_created timestamp (6).
    Username varchar (120) (FK)
    )

    SQL query
    SELECT count (case_id), to_char (cases_created,'MON-YYYY ""), username
    of right outer join tableB, tableA on tableA.username = TableB.username
    I tried using left/right/full, but I don't get what I want.

    Please help me on this.
    Thank you

    Hope that this application solves your condition

    select username,to_char(to_date('01'||months,'dd-mm-yy'),'mon-yy') "Cases created",sum(cnt) "Count of cases" from
    (
    select username,months,1 as cnt from (select lpad(rownum||'-'||yr,5,0) as months from ( select to_char(cases_created,'yy') yr from tableb where rownum<2)
    connect by level<=12) months_tab, tableb
    where to_char(cases_created,'mm-yy')=months
    union all
    select username,months,0 from (select lpad(rownum||'-'||yr,5,0) as months from ( select to_char(cases_created,'yy') yr from tableb where rownum<2)
    connect by level<=12) months_tab, tableb
    where to_char(cases_created,'mm-yy')!=months
    )
    group by username,months
    having months<=(select max(to_char(cases_created,'mm-yy')) from tableb)
    order by username,months asc
    ;
    
    USERNAME      Cases created Count of cases
    
    abc.abc@com   jan-10           1
    abc.abc@com   feb-10           2
    abc.abc@com   mar-10          0
    def.def@com   jan-10            0
    def.def@com   feb-10           1
    def.def@com   mar-10          1    
    

    Published by: Nina Prabhu Sep 29, 2011 23:55
    changed the code to numbers diaplat months on words

    months 'Case created' ===> to_char (to_date ('01' | month, "dd-mm-yy"), 'Mon - yy') 'created '.

  • connect by query, element need root for each line

    Hello

    I'm working on a hierarchical query using connection by front. Each node in the tree has two properties, a type and a sequence.

    The table that contains the hierarchy has 4 fields:
    element_type_from
    element_sequence_from
    element_type_to
    element_sequence_to

    Each child has a parent, a parent can have several childeren. For a map, the element_type_to and element_sequence_to fields are zero.

    To generate a tree, you can run:
    select element_type_to
    ,      element_sequence_to
    from   element_hierarchy
    start with element_type_from = [root_element_type]
           and element_sequence_from = [root_element_sequence]
    connect by prior element_type_to = element_type_from
           and prior element_sequence_to = element_sequence_from
    That works well... but... not only don't want child elements, I would like to return the sequence of element root for each child (in our table is a type of root element is always the same). There are several root elements and I want to create a list containing all the trees and each node in the tree must have its roots as well.

    There is the possibility to use sys_connect_by_path. This returns the root, but also the full path to the current child. It also returns a varchar2, requiring to be substr-ed and to_number-ed to get the sequence... not nice.

    warning, extremely ugly (but functional) code:
    select element_type_to
    ,      element_sequence_to
    ,      to_number(substr(sys_connect_by_path(element_sequence_from ,','),2,instr(sys_connect_by_path(element_sequence_from ,',') ||',',',',2)-2)) root_sequence
    from   element_hierarchy
    start with element_type_from = [root_element_type]
           and element_sequence_from = ( select [root_element_sequence] from all_root_elements )
    connect by prior element_type_to = element_type_from
           and prior element_sequence_to = element_sequence_from
    There must be something simple I'm missing here! Can you help me?

    Edit: Oops, the database version is 10.2.0.4.0

    CONNECT_BY_ROOT maybe?

Maybe you are looking for