nested query sup

Hello
How to write ro nested several rows (row should be composed of a range of values) query sub between the tables if they have no common column.
Based on this range of weight that I consolidate other columns.

For example:
My table should contain

weight range:
-------------------
1 > 2
2 > 3
3 > 4
.
.
.
etc.

Please repost your question adding clarity and an example so that we can understand what you're asking. Also include your full version number.

SELECT * FROM v$version;

Tags: Database

Similar Questions

  • Count (*) with the nested query

    Hello
    I have a question about the count (*) with the nested query.

    I have a table T1 with these columns:
    Number of C1
    Number of C2
    Number of C3
    Number of C4
    Number of C5

    (The type of each column is not relevant for example).

    This query:
    Select C1, C2, C3, C4
    from T1
    Group C1, C2

    It is not correct becausa C3 and C4 are the columns specified in the GROUP BY expression.

    If you run this query:
    Select count (*)
    (select C1, C2, C3, C4
    from T1
    Group C1, C2)

    I don't have an error message (properly, the result is the number of records).

    Why?

    Thank you.

    Best regards
    Luca

    because the optimizer rewrites as

    SELECT     COUNT(*)
                  FROM   T1
              GROUP BY   C1, C2  
    

    G.

    Edited by: g. March 1, 2011 09:19

  • performance for this convoluted nested query

    Hello

    I wonder about the performance of this convoluted nested query:

    Select t.parentId from TreeParentChild t
    where t.childId =: childId and t.childOwnerId in)
    Select tt.parentOwnerId in the TreeParentOwner tt
    where t.parentId = tt.parentId
    )

    There are two tables of interest. The first establishes parent-child relationships,
    and includes the id of the owner of the 'child', which always has exactly one owner.

    table TreeParentChild
    ---------------------
    long parentId
    long childId
    long childOwnerId

    The other table lists of owners for the 'parents' who gave
    parentId can have several owners mapped into multiple lines

    table TreeParentOwner
    ---------------------
    long parentId
    long parentOwnerId

    And the purpose of the above query is to get all the parentids for a given childid
    who have an owner mapping said that the parentid has an owner that is
    the owner of the child.

    This query makes sense to me, but I wonder about his performance, because a column
    external selection corresponds to a column in the internal selection. What is - c
    also called nested request type?

    Andy

    Hi, Andy.

    If you are interested in the jargon, a join where you not actually select anything from one of the tables is called a join semi .

    user9990110 wrote:
    ... It must also pin to a childId data so I've rewritten as:

    SELECT     t.parentId
    FROM     TreeParentChild t
    WHERE     t.childId = :childId AND (t.parentId, t.childOwnerId) IN
         (
              SELECT     tt.parentId, tt.parentOwnerId
              FROM     TreeParentOwner tt
         )
    ;
    

    Is this correct?

    Oops! I forgot this condition: it takes only!
    Yes, your correction is correct.

    And what you would like the clues in this case for 2 tables for better performance?

    Similarly, what would you as clues to the two tables for better performance in the case of the solution to join internal you gave?

    For each query, you can use a composite index on t (parentId, childOwnerId) and an index composed on tt (parentId, parentOwnerId).

    There is yet another way to do what you want: an EXISTS subquery.

    SELECT     t.parentId
    FROM     TreeParentChild          t
    WHERE     t.childId = :childId
    AND      EXISTS
         (
              SELECT     0
              FROM     TreeParentOwner tt
              WHERE     tt.parentId       = t.parentId
              AND     tt.parentOwnerId  = t.childOwnerId
         )
    ;
    

    With rare exceptions, EXISTS subqueries are always correlated.

    I suspect that the best way to this is the first way I posted, using a join.

  • nested query

    Hello
    I'm stuck in a nested query. My table structure is as below.

    create table a1 (varchar2 (10) c1, c2 varchar2 (10));
    create table a2 (varchar2 (10) c1, c2 varchar2 (10));

    and my data

    insert into a1 values ('1', 'A11');
    insert into a1 values ('2', 'A12');

    insert into a2 values ('1', 'A21');
    Insert in a2 (c2) values ('A22');

    now when I try to extract all records in table A1 with column C1 not in column C1 of table A2 then returning me 0 documents instead of returning the second disc with c1, c2 as '2', 'A12 '.

    Can anyone explain why its happening then?

    Hello

    An explanation for this can be found in the doc below.

    [http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/conditions013.htm]

    If any item in the list that follows a NOT IN operation is null, then all lines are evaluated to FALSE or UNKNOWN, and no row is returned

    Concerning
    Anurag Tibrewal.

    PS: There to learn new things every day.

  • Identifier not valid several nesting query

    For the life of me I can't understand why I am getting an error on the first line (in bold) - something is wrong with my nesting, but I can't understand that. It is an invalid identifier on 'CLIENT' error in line 1 has something to do with my nesting I think. Any help?

    Select * from (select cust. ) Region_ID of

    (select cust_nbr from)

    (select region_id,

    Sum (tot_sales) tot_sales the Group of commands by region_id) reg

    Join

    (select sum (tot_sales) tot_sales, region_id,

    cust_nbr of the order of cust_nbr group, region_id) cust

    on cust.region_id = reg.region_id

    where cust.tot_sales > reg.tot_sales *. 2)) ca

    inner join customer c

    We ca.cust_nbr = c.cust_nbr;

    2776946 wrote:

    I'll edit the select * part so the global query can be likened to an analytic function, but the moment I can't get why my request is not read the alias 'CUST '...

    You must take into account the scope of alias variables

    They are valid from the outside to the inside; not inside out like you trying

  • Subselect query returns "invalid identifier", but the nested query return lines

    I don't think it's a general SQL question.

    Select * from persons where person_id in)

    Select person_id with people whose name = 'Obama' - subquery

    ) and age > 18;

    When I run the subquery, I get:

    ORA-00904: "PERSON_ID": invalid identifier

    00904, 00000 - '% s: invalid identifier '.

    * Cause:

    * Action:

    Error on line: column 5: 8

    This is because the table people do not have the person_id field.

    But when I run the nested together query it returns all the lines in people with the AGE greater than 18.

    How is he succeeds when the subquery is obviously wrong?

    363f652b-263D-4418-933F-74a1d0a41b4c wrote:

    I don't think it's a general SQL question.

    Select * from persons where person_id in)

    Select person_id with people whose name = 'Obama' - subquery

    ) and age > 18;

    When I run the subquery, I get:

    ORA-00904: "PERSON_ID": invalid identifier

    00904, 00000 - '% s: invalid identifier '.

    * Cause:

    * Action:

    Error on line: column 5: 8

    This is because the table people do not have the person_id field.

    But when I run the nested together query it returns all the lines in people with the AGE greater than 18.

    How is he succeeds when the subquery is obviously wrong?

    Yes - this is a general SQL question and ask often enough.

    Correlated subqueries depend on the inner query, be able to see and access to the columns of the outer query. Normally see you referenced in the WHERE clause of the subquery and not in the SELECT clause, but the reference is valid in both places. This works because the columns of the tables in the main query are accessible in the subquery. "Person_id" is probably a column in the table 'people '.

    Which can be a cause of problems 'odd' when the column (in your case "person_id") is more of a table.

    Use an alias in the subquery in the subquery and you will find that it will not succeed.

    See these two articles AskTom where he addresses this specific issue

    http://asktom.Oracle.com/pls/Apex/f?p=100:11:0:P11_QUESTION_ID:3317493900346468494

    http://asktom.Oracle.com/pls/Apex/f?p=100:11:0:P11_QUESTION_ID:155200640564

  • How to add a xmlelements not nested in a nested query xmlelement

    I have the following query prints in a file xml very well:

    Select xmlroot)
    XmlElement
    (
    EMSData,
    XMLAGG
    (

    XMLELEMENT
    (
    year,
    XmlAttributes (calyear),
    XMLAGG
    (
    XmlElement
    (
    meantime,
    XmlAttributes (intervalType as 'Type', 'Value' ValeurIntervalle),
    XmlElement
    (
    data,
    XmlAttributes (selectType as "Select", supplier, mission, instrument),
    XMLFOREST
    (
    bytes,
    files
    )
    )
    )
    ValeurIntervalle desc order, supplier, mission, orderBy, instrument
    )
    )
    calyear desc order
    )
    (), version '1.0') .getClobVal () in l_xml
    FROM MyTable
    Calyear group;

    The output is:
    <? XML version = "1.0"? >
    < EMSDATA >
    < CALYEAR YEAR = "2011" >
    < Type INTERVAL = 'DAY' Value = "320" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 2750877820501 < / BYTES >
    <>273997 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = '319' >
    < Select DATA = 'SYSTEM' >
    < BYTES > 5155961487454 < / BYTES >
    <>378457 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "318" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4606818769422 < / BYTES >
    <>420231 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "317" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 3686199358862 < / BYTES >
    <>399271 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = '316' >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4989867970498 < / BYTES >
    <>406249 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "315" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4027315556027 < / BYTES >
    <>463319 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "314" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4893244762669 < / BYTES >
    <>600252 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < / YEAR >
    < / EMSDATA >

    What I have to do is to add a few items just above the nested element under < YEAR >, i.e.:

    <? XML version = "1.0"? >
    < EMSDATA >
    < DailyStartDate > 28 November 11 < / DailyStartDate >
    < WeeklyStartDate > 29 - SEP - 11 < / WeeklyStartDate >
    < MonthlyStartDate > 1 October 01 < / MonthlyStartDate >
    < CALYEAR YEAR = "2011" >
    < Type INTERVAL = 'DAY' Value = "320" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 2750877820501 < / BYTES >
    <>273997 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = '319' >
    < Select DATA = 'SYSTEM' >
    < BYTES > 5155961487454 < / BYTES >
    <>378457 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "318" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4606818769422 < / BYTES >
    <>420231 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "317" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 3686199358862 < / BYTES >
    <>399271 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = '316' >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4989867970498 < / BYTES >
    <>406249 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "315" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4027315556027 < / BYTES >
    <>463319 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < Type INTERVAL = 'DAY' Value = "314" >
    < Select DATA = 'SYSTEM' >
    < BYTES > 4893244762669 < / BYTES >
    <>600252 FILES < / FILES >
    < / DATA >
    < / INTERVAL >
    < / YEAR >
    < / EMSDATA >

    I can select these separate items of data in the table or I can add them to the XML through a local variable. I tried several ways to add this to my above query but am stuck. If I bring to the table, the field names are dailyStartDate, weeklyStartDate and monthlyStartDate. Again, I only want the distinct values and therefore something for everyone in this XML file rather than enumerate over and over again in the XML.

    Please notify.

    Best,
    NAT

    If you already have the values in variables, why not just do that?

    select xmlroot(
     xmlelement
     (
      EMSData,
      XMLForest(
       v_DailyStartDate as "DailyStartDate",
       v_WeeklyStartDate as "WeeklyStartDate",
       v_MonthlyStartDate as "MonthlyStartDate"
      ),
      XMLAGG
      (
       XMLELEMENT
       (
        year,
    
  • Nested query loop

    I have a question I want to loop through the data and the display. The query is an inner join with a table being the order numbers and the second being more details on each order. They are joined by the order number. I want to do is loop through the data and all the details in the order number of the group. I tried many configurations of nesting, and I had no chance. That's what I'd like to see.

    Number 1
    Point 1
    Point 2
    Point 3

    Order number 2
    Point 1
    Point 2

    Order number 3
    point 1
    Point 2
    Point 3
    Point 4

    Any recommendations?


    Thank you guys! I had tried this approach, but apparently I was doing something wrong before. I had received nesting cfoutput errors and then I got lost in a mess of formatting. Thanks again for the direction.

  • the system passed variable is unable to execute the nested query

    {color: #0000ff} list = text_table.txt



    Cat $liste | all read LINE {color}



    do



    sqlplus-silent szubair/ssz12345 & lt; & lt; EOF & gt; / dev/null 2 & gt; & 1



    set LINE = $LINE



    set pagesize 0 feedback off check out of position off echo off;



    Set serveroutput size 2000;



    ARRAYSIZE Set 3;



    fixed lines 2000;



    Set colsep @ | @ ;



    game of garnish trims



    coil /tmp/SQL.txt;



    Select 'trim('|| column_name ||'),' all_tab_columns where table_name = '& LINE ";



    spool off;



    coil $LINE;



    {color:#ff0000}@sql1.sql & lt;-this request does not accept the $LINE..} Please see in the blue text)



    spool {color}



    output



    EXPRESSIONS OF FOLKLORE



    fact











    ========= SQL1.sql --------------------------------------------------



    Select / * + parallel ALL_ROWS (16) * / trim (IHOSRSUC), trim (PMM_DATETIME), trim (SWITCH_NAME), trim (BSC).



    Trim (indicated), Trim (Sector), Trim (IHO2GATT), Trim (IHO2GSUC), Trim (IHO2GFAL), Trim (IHO2GBLK), Trim (IHO2GREL),



    Trim (IHO2GINT), Trim (IHO3VATT), Trim (IHO3VSUC), Trim (IHO3VFAL), Trim (IHO3VBLK), Trim (IHO3VREL), Trim (IHO3VINT),



    Trim (IHO3DATT), Trim (IHO3DSUC), Trim (IHO3DFAL), Trim (IHO3DBLK), Trim (IHO3DREL), Trim (IHO3DINT), Trim (IHOSPR02),



    Trim (IHOSPR01), Trim (HDROP_INTERC_2V), Trim (HDROP_INTERC_3V), Trim (REC_RELIABILITY_IND), Trim (PART_MAP),



    Trim (PMM_DATESTAMP), Trim (IHOSOCHG)



    a {color: #ff0000} $LINE {color}



    where to_char(PMM_DATESTAMP,'YYYY-MM-DD')=to_char(sysdate-1,'YYYY-MM-DD') and rec_reliability_ind = 1;







    {color: #ff0000} ERROR MESSAGE







    of pmmcounter_db. $LINE



    *



    ERROR on line 7:



    ORA-00911: invalid character



    {color}







    any thoughts?



    {color}

    Published by: shakil_zubair on October 28, 2008 12:38 AM

    >

    I guess that SQL * more is Inline script after the shell has replaced all occurrences of variables, therefore, you might want to try an (untested) approach like this:

    list=text_table.txt
    cat $list | while read LINE
    do
    sqlplus -silent szubair/ssz12345 < /dev/null 2>&1
    define LINE=$LINE
    set pagesize 0 feedback off verify off heading off echo off
    set serveroutput on size 2000
    set arraysize 3
    set lines 2000
    set colsep @|@
    set trim on trims on
    spool sql.txt
    
    select 'trim('||column_name||'),' from all_tab_columns where table_name='&LINE';
    
    spool off
    
    spool temp.txt
    select '$LINE' from dual;
    # if you need to have the object name qualified you need to add it like that
    # select 'owner.$LINE' from dual;
    spool off
    
    spool $LINE
    
    @sql1.sql
    
    spool off
    exit
    EOF
    done
    
    -- SQL1.SQL:
    
    select /*+ ALL_ROWS parallel(16)*/
    @@sql.txt
    from
    @@temp.txt
    where to_char(PMM_DATESTAMP,'YYYY-MM-DD')=to_char(sysdate-1,'YYYY-MM-DD')
    and rec_reliability_ind=1;
    

    Moreover, it is a good idea to post your password here in the forum.

    Kind regards
    Randolf

    Oracle related blog stuff:
    http://Oracle-Randolf.blogspot.com/

    SQLTools ++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676 /.
    http://sourceforge.NET/projects/SQLT-pp/

    Published by: Randolf Geist on October 28, 2008 14:10

    security warning

  • Nested queries

    I have this nested queryy but technology does not produce results as it should. The nested query works fine because I've alerted the values on, but I can't get the nested values to be written in the html code. Here is the code:

     tx.executeSql("select eventdate,strftime('%m',eventdate) as month, strftime('%Y',eventdate) as year from news where flag in ('E','A') and eventdate > '2011-7-6' group by date(eventdate,'start of month','+1 month','-1 day') having eventdate is not null order by date(eventdate,'start of month','+1 month','-1 day')", [],
    
                      function(tx,rs){
                       if(rs.rows.length > 0){
                           for(var i=0;i';
    
                                //alert(row.month+" "+row.year)
    
                                tx.executeSql("select subject,strftime('%m',eventdate) as month, strftime('%w',eventdate) as day from news where strftime('%m',eventdate) = strftime('%m','"+row.eventdate+"') and strftime('%Y',eventdate) = strftime('%Y','"+row.eventdate+"') and flag in ('E','A') order by eventdate", [],
    
                                    function(tx,rs2){
                                    //alert(rs2.rows.length);   
    
                                         for(var p=0;p'+row2.subject+'' ;
                                         }
    
                                    }
                                    , app.onError);
    
                                }
    
                           }//end for loop*/
    
                         showresultDiv.innerHTML += contentDiv+'';
                       }
    
                      }
    
                     , app.onError);
    

    Please can anyone help with this.

    Realizing the nature of the html5 application I decide not not my app like that. I made sure, after the main title are built I use an OnClick event to call a function that forwards the relevant data for me to make a dropdown menu with all the values that I needed to be out all at once on the charge.

  • How to exclude records from the outer query

    My apologies if this was requested. I find no answer. I don't know what terminology should be for that matter.

    In simple terms, I want to use the custom in where clause to select records. Problem is function will fail if applied to old records, as there was no relevant data. I have logic to exclude old records, but the problem is that this process running function before old records are excluded. I tried an inside view to exclude records before their passage in the outer query, but this does not resolve the situation.

    Below shows high level required

    Select x

    tab

    where (condition to exclude the old records)

    and function (tab.y) = value

    If I rewrite as below, still have the problem. Was hoping to exclude former records apply before function.

    Select inn.x

    Of

    (select x,

    There

    tab

    where (condition to exclude the old records)) inn

    where function (inn.y) = value

    Thank you

    Hello

    Including ROWNUM in the result set of the query-void will force the subquery to do first:

    Select inn.x

    Of

    (select x,

    There,

    ROWNUM AS r

    tab

    where (condition to exclude the old records)

    ) inn

    where the function (inn.y) = some_value

    Since ROWNUM depends on the WHERE clause of the query-sup, the query cannot be rewritten to the main to do first query WHERE clause.

  • Need help to add totals and subtotals query that uses ROW_NUMBER OVER()

    Hi all

    We have the following query that is used in a report that generates a list of employees working a certain type of movement.
    The report also includes a column called RN that is used when the pagination for the report.
    What we are trying to do now is to add columns that indicate the total number of hours worked by the employee as well as gran total of hours of work for all employees in the report.

    We tried to add the columns last week and have been able to get the totals by using a group by clause. Only problem is that it has changed the order of the column of RN.
    The RN column must stay in numerical order, since we need to select and display the records for paging.

    Is it possible to get our totals without disturbing our paging RN column?

    BTW, thanks Frank for the addition of the UNPIVOT operator at our request. While other solutions worked, UNPIVOT has been the most effective.

    SEE below, the application and all the sql to create tables and test data.

    Thank you
    George
    SELECT *
      FROM (SELECT COUNT (*) OVER () record_count,
                   ROW_NUMBER ()
                   OVER (
                      ORDER BY
                         e.lname || ', ' || e.fname || ' - ' || e.initials DESC,
                         u.startdate DESC)
                      rn,
                   u.empid,
                   a.area,
                   e.lname,
                   e.fname,
                   e.initials,
                   u.startdate,
                   u.starttime,
                   u.endtime,
                   u.hours,
                   u.minutes
              FROM ((SELECT empid,
                            startpp + day_number - 1 startdate,
                            NULL starttime,
                            NULL endtime,
                            8 hours,
                            0 minutes
                       FROM    schedules s
                            JOIN
                               payperiods pp
                            ON pp.periodid = s.periodid 
    UNPIVOT ( v 
    FOR day_number IN (day1 AS 1
                      ,day2 AS 2
                      ,day3 AS 3
                      ,day4 AS 4
                      ,day5 AS 5
                      ,day6 AS 6
                      ,day7 AS 7
                      ,day8 AS 8
                      ,day9 AS 9
                      ,day10 AS 10
                      ,day11 AS 11
                      ,day12 AS 12
                      ,day13 AS 13
                      ,day14 AS 14)
             ) 
             WHERE SUBSTR (v, 1, 4) = 'SHFT' 
             UNION 
    SELECT l.empid,
           l.startdate,
           TO_CHAR (l.starttime, 'HH24:MI'),
           TO_CHAR (l.endtime, 'HH24:MI'),
           TRUNC (
                24
              * (CASE
                    WHEN l.starttime > l.endtime THEN l.endtime + 1 - l.starttime
                    ELSE l.endtime - l.starttime
                 END))
              hours,
           FLOOR (
                (  ( (l.endtime - l.starttime) * 24 * 60 * 60)
                 -   FLOOR ( ( (l.endtime - l.starttime) * 24 * 60 * 60) / 3600)
                   * 3600)
              / 60)
              minutes
      FROM leavereq l
     WHERE     UPPER (l.leavetype) = 'XYZShift'
           AND l.starttime IS NOT NULL
           AND approval = -1
           AND canceled = 0
    ) U) 
    JOIN employee e ON e.empid = u.empid 
    JOIN areas a ON a.areaid = e.areaid 
    WHERE a.configid = 1000 
    AND (startdate between to_date('4/7/2013','mm/dd/yyyy') and to_date('4/20/2013','mm/dd/yyyy')) 
    ORDER BY e.lname||', '||e.fname||' - '||e.initials DESC ,u.startdate DESC 
    ) WHERE rn BETWEEN 1 AND 75 
    order by rn;
    --------------------------------------------------------------------------------
    OUTPUT CURRENT
    RECORD_COUNT,RN,EMPID,AREA,LNAME,FNAME,INITIALS,STARTDATE,STARTTIME,ENDTIME,HOURS,MINUTES
    12,1,753948,TEST,Three,Employee,E3,4/17/2013,,,8,0
    12,2,753948,TEST,Three,Employee,E3,4/15/2013,,,8,0
    12,3,753948,TEST,Three,Employee,E3,4/12/2013,08:00,12:30,4,30
    12,4,753948,TEST,Three,Employee,E3,4/8/2013,,,8,0
    12,5,753940,TEST,Two,Employee,E2,4/12/2013,08:00,13:45,5,45
    12,6,753940,TEST,Two,Employee,E2,4/11/2013,,,8,0
    12,7,753940,TEST,Two,Employee,E2,4/9/2013,,,8,0
    12,8,753940,TEST,Two,Employee,E2,4/8/2013,,,8,0
    12,9,753938,TEST,One,Employee,O1,4/17/2013,,,8,0
    12,10,753938,TEST,One,Employee,O1,4/12/2013,08:00,14:20,6,20
    12,11,753938,TEST,One,Employee,O1,4/9/2013,,,8,0
    12,12,753938,TEST,One,Employee,O1,4/8/2013,,,8,0
    DESIREE OUTPUT
    RECORD_COUNT,RN,EMPID,AREA,LNAME,FNAME,INITIALS,STARTDATE,STARTTIME,ENDTIME,HOURS,MINUTES,EMPTOTAL,GRANTOTAL
    12,1                 ,753948,TEST,Three,Employee,E3       ,4/17/2013   ,               ,             ,8        ,0           ,28:30         ,88:35
    12                    ,2,753948,TEST,Three,Employee,E3       ,4/15/2013   ,               ,             ,8        ,0           ,28:30         ,88:35
    12                    ,3,753948,TEST,Three,Employee,E3       ,4/12/2013   ,08:00       ,12:30     ,4        ,30         ,28:30         ,88:35
    12                    ,4,753948,TEST,Three,Employee,E3       ,4/8/2013     ,               ,             ,8        ,0           ,28:30         ,88:35
    12                    ,5,753940,TEST,Two,Employee,E2         ,4/12/2013   ,08:00       ,13:45     ,5        ,45         ,29:45         ,88:35
    12                    ,6,753940,TEST,Two,Employee,E2         ,4/11/2013   ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,7,753940,TEST,Two,Employee,E2         ,4/9/2013     ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,8,753940,TEST,Two,Employee,E2         ,4/8/2013     ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,9,753938,TEST,One,Employee,O1         ,4/17/2013   ,               ,             ,8        ,0           ,30:20         ,88:35
    12                    ,10,753938,TEST,One,Employee,O1       ,4/12/2013   ,08:00       ,14:20     ,6        ,20         ,30:20          ,88:35
    12                    ,11,753938,TEST,One,Employee,O1       ,4/9/2013     ,               ,             ,8        ,0           ,30:20          ,88:35
    12                    ,12,753938,TEST,One,Employee,O1       ,4/8/2013     ,               ,             ,8        ,0           ,30:20          ,88:35
    --------------------------------------------------------------------------------
    CREATE THE TABLE PROGRAMS
    (
    SCHEDULEID NUMBER (12) NOT NULL,
    EMPID NUMBER (12) NOT NULL,
    PERIODID VARCHAR2 (6 BYTE) NOT NULL,
    AREAID NUMBER (12) NOT NULL,
    DAY1 VARCHAR2 (50 BYTE),
    DAY 2 VARCHAR2 (50 BYTE).
    DAY 3 VARCHAR2 (50 BYTE).
    DAY4 VARCHAR2 (50 BYTE),
    DAY5 VARCHAR2 (50 BYTE),
    DAY6 VARCHAR2 (50 BYTE),
    DAY 7 VARCHAR2 (50 BYTE).
    JOUR8 VARCHAR2 (50 BYTE),
    DAY9 VARCHAR2 (50 BYTE),
    DAY10 VARCHAR2 (50 BYTE),
    DAY 11 VARCHAR2 (50 BYTE).
    DAY12 VARCHAR2 (50 BYTE),
    J13 VARCHAR2 (50 BYTE),
    DAY14 VARCHAR2 (50 BYTE),
    NOPTIND1 INTEGER DEFAULT 0,
    NOPTIND2 INTEGER DEFAULT 0,
    NOPTIND3 INTEGER DEFAULT 0,
    NOPTIND4 INTEGER DEFAULT 0,
    NOPTIND5 INTEGER DEFAULT 0,
    NOPTIND6 INTEGER DEFAULT 0,
    NOPTIND7 INTEGER DEFAULT 0,
    NOPTIND8 INTEGER DEFAULT 0,
    NOPTIND9 INTEGER DEFAULT 0,
    NOPTIND10 INTEGER DEFAULT 0,
    NOPTIND11 INTEGER DEFAULT 0,
    NOPTIND12 INTEGER DEFAULT 0,
    NOPTIND13 INTEGER DEFAULT 0,
    NOPTIND14 INTEGER DEFAULT 0
    );

    CREATE TABLE PAYPERIODS
    (
    PERIODID VARCHAR2 (6 BYTE) NOT NULL,
    DATE OF STARTPP,
    DATE OF ENDPP
    );

    CREATE TABLE LEAVEREQ
    (
    LEAVEREQID NUMBER (12) NOT NULL,
    EMPID NUMBER (12) NOT NULL,
    STARTDATE DATE,
    DATE STARTTIME,
    END DATE,
    LEAVETYPE VARCHAR2 (50 BYTE),
    DATE REQUESTED,
    ENTIRE DEFAULT 0 APPROVAL
    STOP CRITICAL INTEGER DEFAULT 0,
    CANCELLED INTEGER DEFAULT 0,
    ENTERBY VARCHAR2 (50 BYTE),
    APPROVEDBY VARCHAR2 (50 BYTE),
    DATE OF APPROVEDWHEN,
    REMARKS VARCHAR2 (4000 BYTE),
    APPINI VARCHAR2 (2 BYTE),
    NUMBER (12) ROUND.
    GOAL NUMBER (12).
    FMLA NUMBER (12) DEFAULT 0,
    LEAVEAREAID NUMBER (12).
    ARTICLE26 NUMBER (12) DEFAULT 0,
    ORG_LVREQID NUMBER (12)
    );

    CREATE TABLE EMPLOYEE
    (
    EMPID NUMBER (12) NOT NULL,
    AREAID NUMBER (12) NOT NULL,
    BIDAREA NUMBER (12) NOT NULL,
    LNAME VARCHAR2 (30 BYTE),
    FNAME VARCHAR2 (20 BYTE),
    MI VARCHAR2 (3 BYTE),
    CLASSIFICATION VARCHAR2 (10 BYTE),
    VARCHAR2 (2 BYTE) INITIALS,
    DATE OF EODXYZ,
    DATE OF EODNAT,
    VARCHAR2 (3 BYTE) STATUS,
    TURN VARCHAR2 (3 BYTE),
    RDO1 VARCHAR2 (6 BYTE),
    RDO2 VARCHAR2 (6 BYTE),
    TELEPHONE1 VARCHAR2 (14 BYTE),
    TELEPHONE2 VARCHAR2 (14 BYTE),
    REM VARCHAR2 (75 BYTE) DEFAULT 'NONE. '
    LAST4 NUMBER (12).
    SICKOK INTEGER,
    NOSIGNON INTEGER DEFAULT 0,
    TB VARCHAR2 (4 BYTE),
    SUP NUMBER (12).
    OM NUMBER (12).
    FMLA1 INTEGER,
    FMLA1SDATE DAY,
    FMLA1TYPE NUMBER (12).
    FMLA1HRSLEFT NUMBER (12).
    ADMINTEMP INTEGER,
    LEAVERESTRICT INTEGER,
    SLRESTRICT INTEGER,
    DATE OF SLRESDATE,
    DATE OF SLROCDATE,
    DEVSTATUS INTEGER DEFAULT 0,
    USERNAME VARCHAR2 (50 BYTE),
    PWORD VARCHAR2 (100 BYTE),
    PWORDCHG INTEGER,
    ULEVEL VARCHAR2 (50 BYTE),
    E-MAIL VARCHAR2 (50 BYTE),
    VARCHAR2 (50 BYTE) TEAM.
    ANN VARCHAR2 (50 BYTE),
    DDAY1 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY2 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY3 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY4 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY5 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY6 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY7 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY8 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY9 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY10 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY11 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY12 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY13 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    DDAY14 VARCHAR2 (50 BYTE) DEFAULT 'x ',.
    MOVEDATE DATE,
    OLDAREA VARCHAR2 (50 BYTE),
    GRPQA INTEGER,
    GRPTRNG INTEGER,
    LOGINFLAG INTEGER DEFAULT 0,
    NEWAREAID NUMBER (12).
    DATE OF EFFDATE,
    MODIFIED_BY VARCHAR2 (30 BYTE),
    DATE OF MODIFIED_DATE
    );

    CREATE TABLE SPACES
    (
    AREAID NUMBER (12) NOT NULL,
    CONFIGID NUMBER (12) NOT NULL,
    AREA VARCHAR2 (50 BYTE),
    ROLLUPALLOW INTEGER DEFAULT 0,
    SIGNONAREA INTEGER DEFAULT 0,
    OPDIS INTEGER DEFAULT 0,
    MODIFIED_BY VARCHAR2 (30 BYTE),
    DATE OF MODIFIED_DATE
    );
    --------------------------------------------------------------------------------
    Insert in CALENDARS
    (SCHEDULEID, EMPID, PERIODID, DAY1, AREAID
    DAY 2, DAY 3, DAY 4, DAY5 DAY6.
    DAY7 JOUR8, DAY9, DAY10, DAY 11,.
    J13, DAY14 DAY12, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693744, 753738, '092013', 2003, 'X')
    "SHFT < 1530 > ', ' < 1530 SHFT > ', '1530', '1530', '1530',
    'X', 'X', '1530', '1530', 'SHIFT ',.
    "1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    (0, 0);
    Insert in CALENDARS
    (SCHEDULEID, EMPID, PERIODID, DAY1, AREAID
    DAY 2, DAY 3, DAY 4, DAY5 DAY6.
    DAY7 JOUR8, DAY9, DAY10, DAY 11,.
    J13, DAY14 DAY12, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693745, 753740, '092013', 2003, 'X')
    "SHFT < 1530 > ', ' < 1530 SHFT > ', '1530', 'SHIFT', '1530',
    'X', 'X', '1530', '1530', ' 1530',
    "1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    (0, 0);
    Insert in CALENDARS
    (SCHEDULEID, EMPID, PERIODID, DAY1, AREAID
    DAY 2, DAY 3, DAY 4, DAY5 DAY6.
    DAY7 JOUR8, DAY9, DAY10, DAY 11,.
    J13, DAY14 DAY12, NOPTIND1, NOPTIND2,
    NOPTIND3, NOPTIND4, NOPTIND5, NOPTIND6, NOPTIND7,
    NOPTIND8, NOPTIND9, NOPTIND10, NOPTIND11, NOPTIND12,
    NOPTIND13, NOPTIND14)
    Values
    (3693746, 753748, '092013', 2003, 'X')
    "< 1530 SHFT > ', '1530', '1530', '1530', '1530',.
    'X', 'X', ' SHFT < 1530 > ', '1530', 'SHIFT ',.
    "1530', '1530', 'X', 0, 0,
    0, 0, 0, 0, 0,
    0, 0, 0, 0, 0,
    (0, 0);

    COMMIT;

    Insert into PAYPERIODS
    (PERIODID, STARTPP)
    Values
    ('092013', TO_DATE (APRIL 7, 2013 00:00:00 ',' ' DD/MM/YYYY HH24:MI:SS));))
    COMMIT;

    Insert into LEAVEREQ
    (LEAVEREQID, EMPID, STARTDATE, STARTTIME, ENDTIME,
    LEAVETYPE, REQUEST, APPROVAL, REFUSED, ANNULLED,
    ENTERBY, APPROVEDBY, APPROVEDWHEN, ROUND, FMLA,.
    LEAVEAREAID, 26)
    Values
    (4265804, 753748, TO_DATE (12 APRIL 2013 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), TO_DATE (APRIL 1, 2013 08:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (APRIL 1, 2013 12:30 ',' MM/DD/YYYY HH24:MI:SS'),)
    'XYZShift', TO_DATE (8 April 2013 15:14:39 ',' ' the HH24: MI: SS DD/MM/YYYY), - 1, 0, 0,.
    'GH', 'GH', TO_DATE (8 APRIL 2013 15:18:52 ',' DD/MM/YYYY HH24:MI:SS'), 2, 0,.
    2003, 0);
    Insert into LEAVEREQ
    (LEAVEREQID, EMPID, STARTDATE, STARTTIME, ENDTIME,
    LEAVETYPE, REQUEST, APPROVAL, REFUSED, ANNULLED,
    ENTERBY, APPROVEDBY, APPROVEDWHEN, ROUND, FMLA,.
    LEAVEAREAID, 26)
    Values
    (4265805, 753740, TO_DATE (12 APRIL 2013 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), TO_DATE (APRIL 1, 2013 08:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (APRIL 1, 2013 13:45 ',' DD/MM/YYYY HH24:MI:SS'),)
    'XYZShift', TO_DATE (8 April 2013 15:16:04 ',' ' the HH24: MI: SS DD/MM/YYYY), - 1, 0, 0,.
    'GH', 'GH', TO_DATE (8 APRIL 2013 15:19:49 ',' DD/MM/YYYY HH24:MI:SS'), 2, 0,.
    2003, 0);
    Insert into LEAVEREQ
    (LEAVEREQID, EMPID, STARTDATE, STARTTIME, ENDTIME,
    LEAVETYPE, REQUEST, APPROVAL, REFUSED, ANNULLED,
    ENTERBY, APPROVEDBY, APPROVEDWHEN, ROUND, FMLA,.
    LEAVEAREAID, 26)
    Values
    (4265806, 753738, TO_DATE (12 APRIL 2013 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (APRIL 1, 2013 08:00 ',' DD/MM/YYYY HH24:MI:SS'), TO_DATE (APRIL 1, 2013 14:20 ',' DD/MM/YYYY HH24:MI:SS'),)
    'XYZShift', TO_DATE (8 April 2013 15:17:12 ',' ' the HH24: MI: SS DD/MM/YYYY), - 1, 0, 0,.
    'GH', 'GH', TO_DATE (8 APRIL 2013 15:26:55 ',' DD/MM/YYYY HH24:MI:SS'), 2, 0,.
    2003, 0);
    COMMIT;


    Insert EMPLOYEES
    (EMPID, AREAID, BIDAREA, LNAME, FNAME,
    CLASSIFICATION, INITIALS, EODXYZ, EODNAT, STATUS,
    RDO1, RDO2, REM, SICKOK, NOSIGNON,
    TB, SUP, OM, FMLA1, FMLA1SDATE,
    FMLA1HRSLEFT, ADMINTEMP, LEAVERESTRICT, SLRESTRICT, SLRESDATE,
    SLROCDATE, DEVSTATUS, ULEVEL, E-MAIL, TEAM,
    DDAY1, DDAY2, DDAY3, DDAY4, DDAY5,
    DDAY6, DDAY7, DDAY8, DDAY9, DDAY10,
    DDAY11, DDAY12, DDAY13, DDAY14, MOVEDATE,
    OLDAREA, GRPQA, GRPTRNG, LOGINFLAG MODIFIED_BY,
    MODIFIED_DATE)
    Values
    (753738, 2003, 2003, "one", "Employee",)
    '4_NON_BUE', 'E1', TO_DATE (1 JANUARY 2002 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), TO_DATE (JANUARY 1, 2001 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), 'YES ', HE SAID.
    'SAM', 'SUN', 'NONE',-1, 0,
    'NONE', 749405, 749405, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    8, 0, 0, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    To_date (January 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'), 0, ' 1000', '[email protected]', '4',
    'X', '1530', '1530', ' 1530 ', ' 1530',
    "1530 ', 'X', 'X', '1530', ' 1530",
    "1530', '1530', '1530', 'X', TO_DATE (MARCH 18, 2013 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'),
    "1392 ', 0, 0, 0, '752910',
    TO_DATE('03/18/2013 12:10:04', 'MM/DD/YYYY HH24:MI:SS'));)
    COMMIT;

    Insert EMPLOYEES
    (EMPID, AREAID, BIDAREA, LNAME, FNAME,
    CLASSIFICATION, INITIALS, EODXYZ, EODNAT, STATUS,
    RDO1, RDO2, REM, SICKOK, NOSIGNON,
    TB, SUP, OM, FMLA1, FMLA1SDATE,
    FMLA1HRSLEFT, ADMINTEMP, LEAVERESTRICT, SLRESTRICT, SLRESDATE,
    SLROCDATE, DEVSTATUS, ULEVEL, E-MAIL, TEAM,
    DDAY1, DDAY2, DDAY3, DDAY4, DDAY5,
    DDAY6, DDAY7, DDAY8, DDAY9, DDAY10,
    DDAY11, DDAY12, DDAY13, DDAY14, MOVEDATE,
    OLDAREA, GRPQA, GRPTRNG, LOGINFLAG MODIFIED_BY,
    MODIFIED_DATE)
    Values
    (753740, 2003, 2003, "two", "Employee",)
    '4_NON_BUE', 'E2', TO_DATE (1 JANUARY 2002 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (JANUARY 1, 2001 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), 'YES ', HE SAID.
    'SAM', 'SUN', 'NONE',-1, 0,
    'NONE', 749405, 749405, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    8, 0, 0, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    To_date (January 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'), 0, ' 1000', '[email protected]', '4',
    'X', '1530', '1530', ' 1530 ', ' 1530',
    "1530 ', 'X', 'X', '1530', ' 1530",
    "1530', '1530', '1530', 'X', TO_DATE (MARCH 18, 2013 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'),
    "1392 ', 0, 0, 0, '752910',
    TO_DATE('03/18/2013 12:10:04', 'MM/DD/YYYY HH24:MI:SS'));)
    COMMIT;

    Insert EMPLOYEES
    (EMPID, AREAID, BIDAREA, LNAME, FNAME,
    CLASSIFICATION, INITIALS, EODXYZ, EODNAT, STATUS,
    RDO1, RDO2, REM, SICKOK, NOSIGNON,
    TB, SUP, OM, FMLA1, FMLA1SDATE,
    FMLA1HRSLEFT, ADMINTEMP, LEAVERESTRICT, SLRESTRICT, SLRESDATE,
    SLROCDATE, DEVSTATUS, ULEVEL, E-MAIL, TEAM,
    DDAY1, DDAY2, DDAY3, DDAY4, DDAY5,
    DDAY6, DDAY7, DDAY8, DDAY9, DDAY10,
    DDAY11, DDAY12, DDAY13, DDAY14, MOVEDATE,
    OLDAREA, GRPQA, GRPTRNG, LOGINFLAG MODIFIED_BY,
    MODIFIED_DATE)
    Values
    (753748, 2003, 2003, "third", "Employee",)
    '4_NON_BUE', 'E3', TO_DATE (1 JANUARY 2002 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), TO_DATE (JANUARY 1, 2001 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'), 'YES ', HE SAID.
    'SAM', 'SUN', 'NONE',-1, 0,
    'NONE', 749405, 749405, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    8, 0, 0, 0, TO_DATE (JANUARY 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'),
    To_date (January 1, 2013 00:00:00 "," MM/DD/YYYY HH24:MI:SS'), 0, ' 1000', '[email protected]', '4',
    'X', '1530', '1530', ' 1530 ', ' 1530',
    "1530 ', 'X', 'X', '1530', ' 1530",
    "1530', '1530', '1530', 'X', TO_DATE (MARCH 18, 2013 00:00:00 ',' DD/MM/YYYY HH24:MI:SS'),
    "1392 ', 0, 0, 0, '752910',
    TO_DATE('03/18/2013 12:10:04', 'MM/DD/YYYY HH24:MI:SS'));)
    COMMIT;

    Insert areas
    (AREAID CONFIGID, AREA, ROLLUPALLOW, SIGNONAREA,
    OPDIS)
    Values
    (2003, 1000, 'TEST',-1, 0,
    -1) ;
    COMMIT;
    ------------------------------------------------------------------------------------------------

    Published by: George Heller on April 8, 2013 13:32

    Published by: George Heller on April 8, 2013 14:35

    Published by: George Heller on April 8, 2013 14:49

    Hi, George.

    George Heller wrote:
    Hi all

    We have the following query that is used in a report that generates a list of employees working a certain type of movement.


    The report also includes a column called RN that is used when the pagination for the report.
    What we are trying to do now is to add columns that indicate the total number of hours worked by the employee as well as gran total of hours of work for all employees in the report.

    We tried to add the columns last week and have been able to get the totals by using a group by clause. Only problem is that it has changed the order of the column of RN.

    Please your postal code. It is very difficult for me to say what you're doing wrong when I don't know what you're doing.

    The RN column must stay in numerical order, since we need to select and display the records for paging.

    Is it possible to get our totals without disturbing our paging RN column?

    If you mix the aggregate functions and analytical in the query (sub-), the clause GROUP BY is applied and aggregate functions are calculated before the analytical functions are calculated. If you need to calculate the analytical functions first, calculate them in a subquery and make the GROUP BY and aggregate functions in a query Super.

    In this case, it may be simpler to use the analytical SUM, rather than the SUM function.

    SEE below, the application and all the sql to create tables and test data.

    Thank you; It is very useful.
    It would be even more useful if you included only the columns you really need, for the party, you don't already know how to do. For example, it seems that you need only to display 2 columns and area areaid to the table areas. ConfigId can be very important for this request, but you already know what to do with configid? It seems that the other columns of this table play no role in this issue and comes confusion.

    The average time for a first response on this forum is less than 10 minutes. I think people did flee seeing siuch a long message.

    ...
    TRUNC (
    24
    * (CASE
    WHEN l.starttime > l.endtime THEN l.endtime + 1 - l.starttime
    ELSE l.endtime - l.starttime
    END))
    hours,
    

    Why do you enter startime after endtime? If they are on separate days, record the days exactly.

    ...
    WHERE     UPPER (l.leavetype) = 'XYZShift'
    

    The expression to the left of the = sign is guaranteed not to contain all small letters, so it will never equal to "XYZShift".

    ...
    ORDER BY e.lname||', '||e.fname||' - '||e.initials DESC ,u.startdate DESC 
    

    A clause using ORDER BY in this subquery is just a waste of resources. (I'm not talking about analytical clauses ORDER BY;) I mean query ORDER BY clauses, like the one above).

    ) WHERE rn BETWEEN 1 AND 75
    order by rn;
    

    --------------------------------------------------------------------------------
    OUTPUT CURRENT

    RECORD_COUNT,RN,EMPID,AREA,LNAME,FNAME,INITIALS,STARTDATE,STARTTIME,ENDTIME,HOURS,MINUTES
    12,1,753948,TEST,Three,Employee,E3,4/17/2013,,,8,0
    12,2,753948,TEST,Three,Employee,E3,4/15/2013,,,8,0
    12,3,753948,TEST,Three,Employee,E3,4/12/2013,08:00,12:30,4,30
    12,4,753948,TEST,Three,Employee,E3,4/8/2013,,,8,0
    12,5,753940,TEST,Two,Employee,E2,4/12/2013,08:00,13:45,5,45
    12,6,753940,TEST,Two,Employee,E2,4/11/2013,,,8,0
    12,7,753940,TEST,Two,Employee,E2,4/9/2013,,,8,0
    12,8,753940,TEST,Two,Employee,E2,4/8/2013,,,8,0
    12,9,753938,TEST,One,Employee,O1,4/17/2013,,,8,0
    12,10,753938,TEST,One,Employee,O1,4/12/2013,08:00,14:20,6,20
    12,11,753938,TEST,One,Employee,O1,4/9/2013,,,8,0
    12,12,753938,TEST,One,Employee,O1,4/8/2013,,,8,0
    

    I get only 9 rows in the result set when I run your query. Please zip code that you actually run and the results you get in fact.

    DESIREE OUTPUT

    RECORD_COUNT,RN,EMPID,AREA,LNAME,FNAME,INITIALS,STARTDATE,STARTTIME,ENDTIME,HOURS,MINUTES,EMPTOTAL,GRANTOTAL
    12,1                 ,753948,TEST,Three,Employee,E3       ,4/17/2013   ,               ,             ,8        ,0           ,28:30         ,88:35
    12                    ,2,753948,TEST,Three,Employee,E3       ,4/15/2013   ,               ,             ,8        ,0           ,28:30         ,88:35
    12                    ,3,753948,TEST,Three,Employee,E3       ,4/12/2013   ,08:00       ,12:30     ,4        ,30         ,28:30         ,88:35
    12                    ,4,753948,TEST,Three,Employee,E3       ,4/8/2013     ,               ,             ,8        ,0           ,28:30         ,88:35
    

    Do you really want this order, with 'Tw' sorts before 'Th '?

    12                    ,5,753940,TEST,Two,Employee,E2         ,4/12/2013   ,08:00       ,13:45     ,5        ,45         ,29:45         ,88:35
    12                    ,6,753940,TEST,Two,Employee,E2         ,4/11/2013   ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,7,753940,TEST,Two,Employee,E2         ,4/9/2013     ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,8,753940,TEST,Two,Employee,E2         ,4/8/2013     ,               ,             ,8        ,0           ,29:45         ,88:35
    12                    ,9,753938,TEST,One,Employee,O1         ,4/17/2013   ,               ,             ,8        ,0           ,30:20         ,88:35
    12                    ,10,753938,TEST,One,Employee,O1       ,4/12/2013   ,08:00       ,14:20     ,6        ,20         ,30:20          ,88:35
    12                    ,11,753938,TEST,One,Employee,O1       ,4/9/2013     ,               ,             ,8        ,0           ,30:20          ,88:35
    12                    ,12,753938,TEST,One,Employee,O1       ,4/8/2013     ,               ,             ,8        ,0           ,30:20          ,88:35
    

    I think you want something like this:

    WITH   u      AS
    (
         SELECT  empid,
                    startpp + day_number - 1     AS startdate,
                    NULL                             AS starttime,
                    NULL                    AS endtime,
                    8                    AS hours,
                    0                    AS minutes
            FROM    schedules      s
                JOIN    payperiods     pp  ON   pp.periodid = s.periodid
         UNPIVOT ( v
              FOR day_number IN ( day1  AS  1
                                           , day2  AS  2
                                  , day3  AS  3
                                  , day4  AS  4
                                  , day5  AS  5
                                  , day6  AS  6
                                  , day7  AS  7
                                  , day8  AS  8
                                  , day9  AS  9
                                  , day10 AS 10
                                  , day11 AS 11
                                  , day12 AS 12
                                  , day13 AS 13
                                  , day14 AS 14
                          )
                   )
             WHERE   SUBSTR (v, 1, 4) = 'SHFT'
         UNION ALL
            SELECT  empid,
                     startdate,
                     TO_CHAR (starttime, 'HH24:MI'),
                     TO_CHAR (endtime,   'HH24:MI'),
                     TRUNC ( 24
                         * CASE
                                   WHEN starttime > endtime
                       THEN endtime + 1 - starttime
                             ELSE endtime - starttime
                            END
                    )               AS hours,
              MOD ( FLOOR ( (endtime - starttime)
                             * 24 * 60
                       )
                  , 60
                  )               AS minutes
            FROM    leavereq     l
          WHERE   UPPER (leavetype) = 'XYZSHIFT'
                AND     starttime          IS NOT NULL
                AND     approval         = -1
                AND     canceled         = 0
    )
    ,     join_results     AS
    (
         SELECT  COUNT (*) OVER () record_count,
                        ROW_NUMBER () OVER ( ORDER BY  e.lname          DESC
                                   ,            e.fname           DESC
                             ,            e.initials      DESC
                             ,         u.startdate     DESC
                             )        AS rn,
                    u.empid,
                    a.area,
                    e.lname,
                    e.fname,
                    e.initials,
                    u.startdate,
                    u.starttime,
                    u.endtime,
                    u.hours,
                    u.minutes,
              ( 60 * SUM (u.hours)   OVER (PARTITION BY  e.empid)
              )    + SUM (u.minutes) OVER (PARTITION BY  e.empid)     AS emp_minutes,
              ( 60 * SUM (u.hours)   OVER ()
              )    + SUM (u.minutes) OVER ()                    AS grand_minutes
            FROM     u
         JOIN     employee  e  ON   e.empid     = u.empid
         JOIN     areas        a  ON   a.areaid     = e.areaid
         WHERE     a.configid   = 1000
         AND     startdate    BETWEEN TO_DATE ('4/7/2013',  'mm/dd/yyyy')
                        AND     TO_DATE ('4/20/2013', 'mm/dd/yyyy')
    )
    SELECT       record_count,     rn,        empid,     area,    lname, fname,
           initials,     startdate, starttime, endtime, hours, minutes,
           TRUNC (emp_minutes   / 60) || ':'
                                      || TO_CHAR ( MOD (emp_minutes, 60)
                                       , 'FM00'
                                  )     AS emptotal,
           TRUNC (grand_minutes / 60) || ':'
                                      || TO_CHAR ( MOD (grand_minutes, 60)
                                       , 'FM00'
                                  )     AS grandtotal
    FROM       join_results
    WHERE       rn     BETWEEN      1
              AND     75
    ORDER BY  rn
    ;
    
  • Why is query on Table XMLTYPE ACME_CUST do a full Table Scan?

    Our Oracle 11 g Enterprise Edition Release 11.2.0.1.0 database, there is a query against a record in 25 214 table XMLTYPE ACME_CUST.
    SELECT rownum   AS seq,
          EID  AS eid,
          SUBSTR(CUST_ID, 1, INSTR(CUST_ID, '|')-1) AS tgt_acme_customer_id,
          SUBSTR(CUST_ID, INSTR(CUST_ID, '|')   +1) AS src_acme_customer_id_list
        FROM
          (SELECT ac.eid EID,
            listagg(ac.acme_cust_id, '|') WITHIN GROUP (
          ORDER BY ac.acme_cust_id, ac.acme_cust_id) CUST_ID
          FROM ACME_CUST ac
          GROUP BY ac.eid
          HAVING COUNT(ac.acme_cust_id)>1)
    Explain the plan indicates:

    SELECT statement
    County
    VIEW
    FILTER
    Filter predicates
    Count (*) > 1
    GROUP SORT BY
    ACME_CUST FOR FULL TABLE

    The ACME_CUST Table has a virtual column defined on acme_cust_id as well as a corresponding index. He filed is also defined as the primary key.

    Here is the table reflect and associated States:
    CREATE
      TABLE "N98991"."ACME_CUST" OF XMLTYPE
      (
        CONSTRAINT "ACME_CUST_ID_PK" PRIMARY KEY ("ACME_CUST_ID") USING INDEX
        PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536
        NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1
        FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE
        DEFAULT) TABLESPACE "ACME_DEV" ENABLE
      )
      XMLTYPE STORE AS SECUREFILE BINARY XML
      (
        TABLESPACE "ACME_DEV" ENABLE STORAGE IN ROW CHUNK 8192 CACHE READS LOGGING
        NOCOMPRESS KEEP_DUPLICATES STORAGE(INITIAL 106496 NEXT 1048576 MINEXTENTS 1
        MAXEXTENTS 2147483645 PCTINCREASE 0 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT)
      )
      ALLOW NONSCHEMA ALLOW ANYSCHEMA VIRTUAL COLUMNS
      (
        "EID" AS (CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(XMLQUERY(
        'declare default element namespace "http://www.cigna.com/acme/domains/customer/customerprofile/2011/11"; (::)                               
    /customerProfile/@eid'
        PASSING BY VALUE SYS_MAKEXML(128,"XMLDATA") RETURNING CONTENT ),0,0,
        16777216,0),50,1,2) AS VARCHAR2(15))),
      *bold*  "ACME_CUST_ID" AS (CAST(SYS_XQ_UPKXML2SQL(SYS_XQEXVAL(XMLQUERY(
        'declare default element namespace "http://www.cigna.com/acme/domains/customer/customerprofile/2011/11"; (::)                               
    /customerProfile/@id' *bold*
        PASSING BY VALUE SYS_MAKEXML(128,"XMLDATA") RETURNING CONTENT ),0,0,
        16777216,0),50,1,2) AS VARCHAR2(50))),
        "CRET_DT" AS (SYS_EXTRACT_UTC(CAST(TO_TIMESTAMP_TZ(SYS_XQ_UPKXML2SQL(
        SYS_XQEXVAL(XMLQUERY(
        'declare default element namespace "http://www.cigna.com/acme/domains/customer/customerprofile/2011/11"; (::)                                                                                                       
    /customerProfile/@create_dt'
        PASSING BY VALUE SYS_MAKEXML(128,"XMLDATA") RETURNING CONTENT ),0,0,
        16777216,0),50,1,2),'SYYYY-MM-DD"T"HH24:MI:SS.FFTZH:TZM') AS TIMESTAMP
    WITH
      TIME ZONE)))
      )
      PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE
      (
        INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0
        FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT
      )
      TABLESPACE "ACME_DEV" ;
    CREATE
      INDEX "N98991"."ACME_CST_CRET_DT_IDX" ON "N98991"."ACME_CUST"
      (
        "CRET_DT"
      )
      PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE
      (
        INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0
        FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT
      )
      TABLESPACE "ACME_DEV" ;
    CREATE
      INDEX "N98991"."ACME_CST_EID_IDX" ON "N98991"."ACME_CUST"
      (
        "EID"
      )
      PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE
      (
        INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0
        FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT
      )
      TABLESPACE "ACME_DEV" ;
    *bold*CREATE UNIQUE INDEX "N98991"."ACME_CUST_ID_PK" ON "N98991"."ACME_CUST"
      (
        "ACME_CUST_ID"
      )
      PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE *bold*
      (
        INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0
        FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT
      )
      TABLESPACE "ACME_DEV" ;
      CREATE
        INDEX "N98991"."ACME_CUST_XMLINDEX_IX" ON "N98991"."ACME_CUST"
        (
          OBJECT_VALUE
        )
        INDEXTYPE IS "XDB"."XMLINDEX" PARAMETERS
        (
          'XMLTABLE ACME_CUST_IDX_TAB XMLNamespaces (''http://www.cigna.com/acme/domains/commoncontact/2011/11'' as "cm",  default ''http://www.cigna.com/acme/domains/customer/customerprofile/2011/11''),       
    ''/customerProfile''        
    columns       
    DOB date  PATH ''personInformation/cm:birthDate'',       
    FIRSTNAME varchar2(40)    PATH ''name/cm:givenName'',       
    LASTNAME varchar2(40)    PATH ''name/cm:surName'',       
    SSN varchar2(30)    PATH ''identifiers/ssn'',       
    MEMBERINFOS XMLType path ''memberInfos/memberInfo'' VIRTUAL        
    XMLTable acme_cust_lev2_idx_tab XMLNAMESPACES(default ''http://www.cigna.com/acme/domains/customer/customerprofile/2011/11''),       
    ''/memberInfo'' passing MEMBERINFOS          
    columns          
    ami varchar2(40) PATH ''ami'',         
    subscId varchar2(50) PATH ''clientRelationship/subscriberInformation/subscriberId'',         
    employeeId varchar2(50) PATH ''systemKeys/employeeId'',         
    clientId varchar2(50) PATH ''clientRelationship/clientId''       
    '
        );
    CREATE UNIQUE INDEX "N98991"."SYS_C00384339" ON "N98991"."ACME_CUST"
      (
        "SYS_NC_OID$"
      )
      PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE
      (
        INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0
        FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT
        CELL_FLASH_CACHE DEFAULT
      )
      TABLESPACE "ACME_DEV" ;
    CREATE UNIQUE INDEX "N98991"."SYS_IL0000649948C00003$$" ON "N98991"."ACME_CUST"
      (
        PCTFREE 10 INITRANS 2 MAXTRANS 255 STORAGE(INITIAL 65536 NEXT 1048576
        MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST
        GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
        TABLESPACE "ACME_DEV" PARALLEL (DEGREE 0 INSTANCES 0) ;
    Why is it not the ACME_CUST_ID_PK a unique index on the column virtual ACME_CUST_ID used in the plan to explain it?

    Any input would be much appreciated, like really puzzled here.

    Kind regards
    Rick

    Hi Richard,

    Event 10053 appears excessive for this situation.

    What is the problem?
    Set the event, run the query, disconnected the event, check the trace file, that's all.

    It is not excessive if it helps you understand what is happening and why an index is of no use in this situation.

    Tried the / * + INDEX_FFS (ACME_CUST_ID_PK) * / hint in the query "nested".

    Don't know what nested query, you reference, so if I misunderstood what you mean, just ignore the comment.
    What you posted earlier, it seems that you talk about this part:

    listagg(ac.acme_cust_id,'|') WITHIN GROUP (
    ORDER BY ac.acme_cust_id,ac.acme_cust_id) CUST_ID
    

    This isn't a nested query, it's a projection. All major works (recovery of lines) has already been done when it comes to this part.

    Maybe just to accept the performance of the queries because it is...

    Maybe you can try something else.

    See the document: Oracle XML DB: best practices, page 15 exodus 8:

    When there are multiple scalar values that must be consolidated or ordered, it is better to write
    with XMLTable build projecting all the columns to be ordered or grouped as shown
    below.

    Close example of your real need:

    Connected to:
    Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
    
    SQL> create table xtab_cols of xmltype
      2  xmltype store as securefile binary xml;
    
    Table created.
    
    SQL> insert /*+ append */ into xtab_cols
      2  select xmlelement("ROW",
      3           xmlforest(
      4            TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_TYPE_MOD, DATA_TYPE_OWNER,
      5            DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE, COLUMN_ID,
      6            DEFAULT_LENGTH, NUM_DISTINCT, LOW_VALUE, HIGH_VALUE,
      7            DENSITY, NUM_NULLS, NUM_BUCKETS, LAST_ANALYZED, SAMPLE_SIZE,
      8            CHARACTER_SET_NAME, CHAR_COL_DECL_LENGTH,
      9            GLOBAL_STATS, USER_STATS, AVG_COL_LEN, CHAR_LENGTH, CHAR_USED,
     10            V80_FMT_IMAGE, DATA_UPGRADED, HISTOGRAM
     11           )
     12         )
     13  from dba_tab_cols
     14  where owner = 'SYS'
     15  ;
    
    57079 rows created.
    
    SQL> commit;
    
    Commit complete.
    
    SQL> set long 1000
    SQL> set pages 100
    SQL> select xmlserialize(document object_value) from xtab_cols where rownum = 1;
    
    XMLSERIALIZE(DOCUMENTOBJECT_VALUE)
    --------------------------------------------------------------------------------
    
      ACCESS$
      D_OBJ#
      NUMBER
      22
      N
      1
      7454
      C2083A
      C3031D18
      ,000134156157767642
      0
      1
      2012-01-28
      34794
      YES
      NO
      5
      0
      NO
      YES
      NONE
    
    
    SQL> exec dbms_stats.gather_table_stats(user, 'XTAB_COLS');
    
    PL/SQL procedure successfully completed.
    
    SQL> set autotrace traceonly
    SQL> set timing on
    SQL> set lines 120
    SQL> select x.table_name
      2       , listagg(x.column_name, ',') within group (order by column_id)
      3  from xtab_cols t
      4     , xmltable('/ROW' passing t.object_value
      5        columns table_name  varchar2(30) path 'TABLE_NAME'
      6              , column_name varchar2(30) path 'COLUMN_NAME'
      7              , column_id   number       path 'COLUMN_ID'
      8       ) x
      9  group by x.table_name
     10  ;
    
    4714 rows selected.
    
    Elapsed: 00:00:08.25
    
    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 602782846
    
    ---------------------------------------------------------------------------------
    | Id  | Operation           | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    ---------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT    |           |   466M|   101G|  1580K  (3)| 05:16:04 |
    |   1 |  SORT GROUP BY      |           |   466M|   101G|  1580K  (3)| 05:16:04 |
    |   2 |   NESTED LOOPS      |           |   466M|   101G|  1552K  (1)| 05:10:32 |
    |   3 |    TABLE ACCESS FULL| XTAB_COLS | 57079 |    12M|   408   (1)| 00:00:05 |
    |   4 |    XPATH EVALUATION |           |       |       |            |          |
    ---------------------------------------------------------------------------------
    
    Statistics
    ----------------------------------------------------------
              9  recursive calls
              1  db block gets
           1713  consistent gets
              0  physical reads
             96  redo size
         773516  bytes sent via SQL*Net to client
           3873  bytes received via SQL*Net from client
            316  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
           4714  rows processed
    

    And of course, even better after adding an XML index structured (4714 lines read in 1 s):

    SQL> CREATE INDEX xtab_cols_sxi ON xtab_cols (OBJECT_VALUE) INDEXTYPE IS XDB.XMLIndex
      2  PARAMETERS (
      3  q'#XMLTable my_xtab
      4  '/ROW'
      5  columns table_name varchar2(30) path 'TABLE_NAME'
      6        , column_name varchar2(30) path 'COLUMN_NAME'
      7        , column_id number path 'COLUMN_ID' #');
    
    Index created.
    
    Elapsed: 00:00:13.42
    SQL> select x.table_name
      2       , listagg(x.column_name, ',') within group (order by column_id)
      3  from xtab_cols t
      4     , xmltable('/ROW' passing t.object_value
      5        columns table_name  varchar2(30) path 'TABLE_NAME'
      6              , column_name varchar2(30) path 'COLUMN_NAME'
      7              , column_id   number       path 'COLUMN_ID'
      8       ) x
      9  group by x.table_name
     10  ;
    
    4714 rows selected.
    
    Elapsed: 00:00:01.00
    
    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 3303494605
    
    ------------------------------------------------------------------------------
    | Id  | Operation          | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    ------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT   |         | 57520 |  3201K|   174   (3)| 00:00:03 |
    |   1 |  SORT GROUP BY     |         | 57520 |  3201K|   174   (3)| 00:00:03 |
    |   2 |   TABLE ACCESS FULL| MY_XTAB | 57520 |  3201K|   171   (1)| 00:00:03 |
    ------------------------------------------------------------------------------
    
    Note
    -----
       - dynamic sampling used for this statement (level=2)
    
    Statistics
    ----------------------------------------------------------
            297  recursive calls
              1  db block gets
            989  consistent gets
              0  physical reads
            176  redo size
         773516  bytes sent via SQL*Net to client
           3873  bytes received via SQL*Net from client
            316  SQL*Net roundtrips to/from client
             21  sorts (memory)
              0  sorts (disk)
           4714  rows processed
    
  • SELECT query problem

    Hi all

    Need select records less where Rownum < = 100, a table in which the records are classified by a field in a query, but after stopped in the ordering of rownum gets changes.
     
    with t as (select 1 a,'d' b from dual 
    union select 8 a,'t' b from dual 
    union select 3 a,'u' b from dual 
    union select 7 a,'k' b from dual ) 
    select t.*,rownum from t order by 2 ;
    
    
    A B ROWNUM 
    1 d 1 
    7 k 3 
    8 t 4 
    3 u 2 
    Now I want to select records where ronum < = 2 as below, this can be done by changing only in where clause and do not touch the query select, as can do a nested query I but need to do it by changing only in where clause.
     
    A B ROWNUM 
    1 d 1 
    7 k 3 
    Thanks in advance

    Thanks and greetings
    Sanjay

    Published by: Sanjay March 29, 2011 06:26

    Hi, Sanjay

    Sanjay wrote:
    Hi all

    Need select records less where Rownum<= 100,="" from="" a="" table="" in="" which="" records="" are="" ordered="" by="" a="" field="" in="" a="" query="" but="" after="" doing="" order="" by="" the="" rownum="" ordering="" gets="">

    
    with t as (select 1 a,'d' b from dual
    union select 8 a,'t' b from dual
    union select 3 a,'u' b from dual
    union select 7 a,'k' b from dual )
    select t.*,rownum from t order by 2 ;
    
    A B ROWNUM
    1 d 1
    7 k 3
    8 t 4
    3 u 2 
    

    Now I want to select records where ronum<= 2="" like="" below,="" can="" this="" be="" done="" by="" changing="" only="" in="" where="" clause="" and="" not="" touching="" the="" select="" query="" as="" it="" can="" be="" done="" by="" nested="" query="" i="" but="" need="" to="" do="" it="" by="" changing="" only="" in="" where="">

    
    A B ROWNUM
    1 d 1
    7 k 3 
    

    No, there is no way to get these results by changing only the WHERE clause. As it is, you have no column or expression in the main query that indicates how the lines are classified according to b, which is exactly what to test in the WHERE clause. (Remember, ROWNUM is assigned before ORDER BY is done in the same auxiliary request). You must add a using ROWNUM or ROW_NUMBER analytic function. either way requires some preparation to be done in a subquery.

    For example, the following query has an ORDER BY clause, added to the request slot, so that ROWNUM in the main query will be more arbitrary:

    with t as (select 1 a,'d' b from dual
    union select 8 a,'t' b from dual
    union select 3 a,'u' b from dual
    union select 7 a,'k' b from dual
    ORDER BY  b                              -- Added
    )
    SELECT    t.*
    ,       ROWNUM
    FROM        t
    WHERE       ROWNUM     <= 2     -- Added
    ORDER BY  b
    ;
    

    Output:

    `        A B     ROWNUM
    ---------- - ----------
             1 d          1
             7 k          2
    

    It is no coincidence that the numbers in the column ROWNUM are 1 and 2. If you want really to arbitrary numbers (such as 1 and 3), you will need an another subquery.

  • Using the cursor to another (nested cursors) cursor objects...?

    Now, I'm pretty sure that's not possible, but as a last thought of the station, it would not hurt to ask.

    I have a number of fairly complex cursors in PL/SQL (all beautifully packaged upwards), which are used in a number of other different queries for reporting. Because the same cursor is reused several times in different contexts, I want set the cursor once, then use it as a subquery in the other queries. This will also help as if I place the SQL directly in other queries, then it will be necessary propagate the changes to the base query in all other queries which use - and that it will be maintained by a large team that goes forward, it would be wide open to things being missed... (not that I don't trust my colleagues or anything like that...!)

    So, in brief and simple terms, if I;

    CURSOR curDateList (pi_start_date AS, pi_end_date IN DATE)
    IS
    SELECT pi_start_date + rownum - 1 when
    FROM (select '1' sys.dual connects by level < = (pi_end_date - pi_start_date + 1));

    that returns a list of the dates of pi_start_date to pi_end_date, and I want to integrate in another slider like;

    CURSOR curEmpWork (pi_start_date AS, pi_end_date IN DATE)
    IS
    SELECT e.employee_id, dl.when, e.work_pattern
    OF e xxx.emp_work_patterns,.
    DL curDateList (pi_start_date, pi_end_date)
    WHERE dl.when = e.roster_date
    ORDER BY e.roster_date;

    (Needless to say that queries are much more complex and many!)

    I reached the required result by using the pipeline table functions that just open the first cursor and run each line, but am frequently end up using multiple nested functions to achieve and I see marked in this way, then the performance degradation that comes to nest queries within the other runs a lot faster. As a nested query is just a nested cursor, it seems that this is possible, but I'm not only have no chance - I am struggling to find something that says that it of possible or not (which made me think I am barking the wrong tree here!)

    Any help would be greatly appreciated.

    No, it is not possible, but have you thought of creating a view instead?

Maybe you are looking for