How to mention index in select query?

Hi All,
   If I am using fields of two diffrent secondary index in a single select query on a table how I can mention that data should be picked according to first index used in the query?
Regards
Deepak

Please search before asking basic questions.
Thread locked.
Rob

Similar Messages

  • How to enforce index in oracle query

    Hi all
    how to enforce index in oracle query
    Regards

    Use INDEX hint to force Optimizer to use the specfied index.
    You really need to investigate why Optimizer doesn't choose the index. Remember, INDEX SCAN are not always GOOD.
    Jaffar

  • How to utilize index in selection statement

    hi
    how to utilize index in selection statement and how is it reduces performance whether another alternative is there to reduce performance .
    thanks

    Hi Suresh,
    For each SQL statement, the database optimizer determines the strategy for accessing data records. Access can be with database indexes (index access), or without database indexes (full table scan).The cost-based database optimizer determines the access strategy on the basis of:
    *Conditions in the WHERE clause of the SQL statement
    *Database indexes of the table(s) affected
    *Selectivity of the table fields contained in the database indexes
    *Size of the table(s) affected
    *The table and index statistics supply information about the selectivity of table fields, the selectivity of combinations of table fields, and table size.     Before a database access is performed, the database optimizer cannot calculate the exact cost of a database access. It uses the information described above to estimate the cost of the database access.The optimization calculation is the amount by which the data blocks to be read (logical read accesses) can be reduced. Data blocks show the level of detail in which data is written to the hard disk or read from the hard disk.
    <b>Inroduction to Database Indexes</b>
    When you create a database table in the ABAP Dictionary, you must specify the combination of fields that enable an entry within the table to be clearly identified. Position these fields at the top of the table field list, and define them as key fields.
    After activating the table, an index is created (for Oracle, Informix, DB2) that consists of all key fields. This index is called a primary index. The primary index is unique by definition. As well as the primary index, you can define one or more secondary indexes for a table in the ABAP Dictionary, and create them on the database. Secondary indexes can be unique or non-unique. Index records and table records are organized in data blocks.
    If you dispatch an SQL statement from an ABAP program to the database, the program searches for the data records requested either in the database table itself (full table scan) or by using an index (index unique scan or index range scan). If all fields requested are found in the index using an index scan, the table records do not need to be accessed.
    A data block shows the level of detail in which data is written to the hard disk or read from the hard disk. Data blocks may contain multiple data records, but a single data record may be spread across several data blocks.
    Data blocks can be index blocks or table blocks. The database organizes the index blocks in the form of a multi-level B* tree. There is a single index block at root level, which contains pointers to the index blocks at branch level. The branch blocks contain either some of the index fields and pointers to index blocks at leaf level, or all index fields and a pointer to the table records organized in table blocks. The index blocks at leaf level contain all index fields and pointers to the table records from the table blocks.
    The pointer that identifies one or more table records has a specific name. It is called, for example, ROWID for Oracle databases. The ROWID consists of the number of the database file, the number of the table block, and the row number within the table block.
    The index records are stored in the index tree and sorted according to index field. This enables accelerated access using the index. The table records in the table blocks are not sorted.
    An index should not consist of too many fields. Having a few very selective fields increases the chance of reusability, and reduces the chance of the database optimizer selecting an unsuitable access path.
    <b>Index Unique Scan</b>
    If, for all fields in a unique index (primary index or unique secondary index), WHERE conditions are specified with '=' in the WHERE clause, the database optimizer selects the access strategy index unique scan.
    For the index unique scan access strategy, the database usually needs to read a maximum of four data blocks (three index blocks and one table block) to access the table record.
    <b><i>select * from VVBAK here vbeln = '00123' ......end select.</i></b>
    In the SELECT statement shown above, the table VVBAK is accessed. The fields MANDT and VBELN form the primary key, and are specified with '=' in the WHERE clause. The database optimizer therefore selects the index unique scan access strategy, and only needs to read four data blocks to find the table record requested.
    <b>Index Range Scan</b>
    <b><i>select * from VVBAP here vbeln = '00123' ......end select.</i></b>
    In the example above, not all fields in the primary index of the table VVBAP (key fields MANDT, VBELN, POSNR) are specified with '=' in the WHERE clause. The database optimizer checks a range of index records and deduces the table records from these index records. This access strategy is called an index range scan.
    To execute the SQL statement, the DBMS first reads a root block (1) and a branch block (2). The branch block contains pointers to two leaf blocks (3 and 4). In order to find the index records that fulfill the criteria in the WHERE clause of the SQL statement, the DBMS searches through these leaf blocks sequentially. The index records found point to the table records within the table blocks (5 and 6).
    If index records from different index blocks point to the same table block, this table block must be read more than once. In the example above, an index record from index block 3 and an index record from index block 4 point to table records in table block 5. This table block must therefore be read twice. In total, seven data blocks (four index blocks and three table blocks) are read.
    The index search string is determined by the concatenation of the WHERE conditions for the fields contained in the index. To ensure that as few index blocks as possible are checked, the index search string should be specified starting from the left, without placeholders ('_' or %). Because the index is stored and sorted according to the index fields, a connected range of index records can be checked, and fewer index blocks need to be read.
    All index blocks and table blocks read during an index range scan are stored in the data buffer at the top of a LRU (least recently used) list. This can lead to many other data blocks being forced out of the data buffer. Consequently, more physical read accesses become necessary when other SQL statements are executed
    <b>DB Indexex :Concatenation</b>
         In the concatenation access strategy, one index is reused. Therefore, various index search strings also exist. An index unique scan or an index range scan can be performed for the various index search strings. Duplicate entries in the results set are filtered out when the search results are concatenated.
    <i><b>Select * from vvbap where vbeln in ('00123', '00133', '00134').
    endselect.</b></i>
    In the SQL statement above, a WHERE condition with an IN operation is specified over field VBELN. The fields MANDT and VBELN are shown on the left of the primary index. Various index search strings are created, and an index range scan is performed over the primary index for each index search string. Finally, the result is concatenated.
    <b>Full Table Scan</b>
    <b><i>select * from vvbap where matnr = '00015'.
    endselect</i></b>
    If the database optimizer selects the full table scan access strategy, the table is read sequentially. Index blocks do not need to be read.
    For a full table scan, the read table blocks are added to the end of an LRU list. Therefore, no data blocks are forced out of the data buffer. As a result, in order to process a full table scan, comparatively little memory space is required within the data buffer.
    The full table scan access strategy is very effective if a large part of a table (for example, 5% of all table records) needs to be read. In the example above, a full table scan is more efficient than access using the primary index.
    <i><b>In Brief</b></i>
    <i>Index unique scan:</i> The index selected is unique (primary index or unique secondary index) and fully specified. One or no table record is returned. This type of access is very effective, because a maximum of four data blocks needs to be read.
    <i>Index range scan:</i> The index selected is unique or non-unique. For a non-unique index, this means that not all index fields are specified in the WHERE clause. A range of the index is read and checked. An index range scan may not be as effective as a full table scan. The table records returned can range from none to all.
    <i>Full table scan:</i> The whole table is read sequentially. Each table block is read once. Since no index is used, no index blocks are read. The table records returned can range from none to all.
    <i>Concatenation:</i> An index is used more than once. Various areas of the index are read and checked. To ensure that the application receives each table record only once, the search results are concatenated to eliminate duplicate entries. The table records returned can range from none to all.
    Regards,
    Balaji Reddy G
    ***Rewards if answers are helpful

  • How can i use index in select query.. facing problem with the select query.

    Hi Friends,
    I am facing a serious problem in one of the select query. It is taking a lot of time to fetch data in Production Scenario.
    Here is the query:
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelat LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelatrprctr
        WHERE rldnr  = c_telstra_accounting
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          And rzzlstar in r_lstar                            
          AND rpmax  = c_max_period.
    There are 5 indices present for Table ZTFTELAT.
    Indices of ZTFTELAT:
      Name   Description                                               
      0        Primary key( RCLNT,RLDNR,RRCTY,RVERS,RYEAR,ROBJNR,SOBJNR,RTCUR,RUNIT,DRCRK,RPMAX)                                          
      005    Profit (RCLNT,RPRCTR)
      1        Ledger, company code, account (RLDNR,RBUKRS, RACCT)                                
      2        Ledger, company code, cost center (RLDNR, RBUKRS,RCNTR)                           
      3        Account, cost center (RACCT,RCNTR)                                        
      4        RCLNT/RLDNR/RRCTY/RVERS/RYEAR/RZZAUFNR                        
      Z01    Activity Type, Account (RZZLSTAR,RACCT)                                        
      Z02    RYEAR-RBUKRS- RZZZBER-RLDNR       
    Can anyone help me out why it is taking so much time and how we can reduce it ? and also tell me if I want to use index number 1 then how can I use?
    Thanks in advance.

    Hi Shiva,
    I am using two more select queries with the same manner ....
    here are the other two select query :
    ***************1************************
    SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelpt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelptrprctr
        WHERE rldnr  = c_telstra_projects
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar             
          AND rpmax  = c_max_period.
    and the second one is
    *************************2************************
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelnt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelntrprctr
        WHERE rldnr  = c_telstra_networks
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar                              
          AND rpmax  = c_max_period.
    for both the above table program is taking very less time .... although both the table used in above queries have similar amount of data. And i can not remove the APPENDING CORRESPONDING. because i have to append the data after fetching from the tables.  if i will not use it will delete all the data fetched earlier.
    Thanks on advanced......
    Sourabh

  • How to use offset in select query

    Suppose i have data like ssonje     00000001 as a one field in database table . i have to segregate this two data. how should I do this.the first part is of 12 characters and the last is of 10 character long.

    Hi Naveen,
    I am again in trouble, Now the requirement were changed. I am sending you the code which i had implemented.
    Now, the user enter username(ie UNAMED) and document id (ie. TEMPD) and the output should be doucment id, which has been search through database table RFDT , field SRTFD, this field contains both the username and the document id.
    That means: suppose user enters UNAMED as SSONJE and TEMPD as 0000000030, then i want to fier the select query from RFDT on field SRTFD and get only the document id of that user which user enter on input field-UNAMED.
    i had tried but result were not coming.
    please go through the code.
    data:uname type UF05A-UNAMD.
    data:temp type UF05A-TEMPD.
    TYPES: BEGIN OF TEITAB_RFDT,
           SRTFD TYPE RFDT-SRTFD,
           END OF TEITAB_RFDT.
    DATA: ITAB_RFDT TYPE TABLE OF TEITAB_RFDT.
    DATA: WA_RFDT TYPE TEITAB_RFDT.
    DATA: STR(22) TYPE c.
    SELECT-OPTIONS:UNAMED FOR uname,
    TEMPD FOR TEMP.
    UNAMED-option = 'CP'.
    append UNAMED.
    CONCATENATE UNAMED TEMPD INTO STR.
    SELECT SRTFD FROM RFDT INTO CORRESPONDING FIELDS OF TABLE ITAB_RFDT WHERE SRTFD eq str.
    LOOP AT ITAB_RFDT INTO WA_RFDT.
    SPLIT WA_RFDT AT SPACE INTO STR1 STR2.
      WRITE: / STR1,STR2.
    ENDLOOP.
    Please mentioned what is the way to do this.
    Thanks

  • How to get result of select query from  oracle  in VC

    Dear All ,
    I have a application in oracle which insert the data in the oracle database table.
    Now i want to show all the data that has been inserted into the database table in my VC application but i don't know how to handle select query in VC.
    Regards
    Krishan

    Hi Goivndu
    Thanks for your reply .
    I know all those things.
    I have created the system & alias  for my backend oracle system.
    I can also see all the stored procedure that are there in my oracle system.
    I just want to know how to write a select query in a stored procedure .
    you can insert data , Update data through oracle procedure but i don't think there is any way to get the result of select query in stored procedure .
    If you know any way to do that please do let me know .
    Regards
    Krishan

  • How to put loop in select query..?

    Hi All,
    I am setting select query which CRecordSet is going to execute.
    Existing query is,
    Select branchNumber,Count(*) from branches where branchNumber = %d and dowloadType >%d;  
    Here %d is getting filled every time with new value. Now this query is getting execute 500 times if 500 branches are there.
    We want to improve performance. and want branchnumber and count(*) in One go.
    something like, 
    select branchNumber,Count(*) from Branches where 
    (branch =1 and dowloadType >2)
    (branch =2 and dowloadType >100)
     (branch =3 and dowloadType >234)
    how can we do that?
    Kindly help me on this.
    Thanks,
    Sachin.

    Thanks For reply. but here values are coming from different collection from source code.
    For e.g.  Map[branchNumber][DownloadType] = [1,233],[2,444],[30,234],[5,456].
    Now these values i need to insert at the place of  S.branch   and    S.DownloadType                              
    SELECT GB.Branch ,
    COUNT(*)
    FROM @Sample S
    INNER JOIN @GroupBy GB ON GB.Branch = (value from map)
    AND GB.DownloadType < (value from map)
    GROUP BY GB.Branch;

  • How to ignore zero in select query

    select * from EINA where  EINAMATNR = <b>yyyy</b> and EINALIFNR = <b>zzzz</b>
    In select query, how to ignore zero? for example, EINAMATNR = 0000000yyyy, EINALIFNR=000zzz
    Maybe I can use LIKE keyword in sql query. Any other way?
    Thanks.

    Use the following conversion routines to convert yyyy & zzzz  to remove the leading zeros and then pass it to your select query.
    For Matnr -> CONVERSION_EXIT_MATN1_INPUT
    For LIFNR ->CONVERSION_EXIT_alpha_input.
       CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
            EXPORTING
              input  = yyyy
            IMPORTING
              output = t_lifnr.
          CALL FUNCTION 'CONVERSION_EXIT_MATN1_INPUT'
            EXPORTING
              input  = zzzz
            IMPORTING
              output = t_matnr.
    select * from EINA where EINA~MATNR = t_matnr  and EINA~LIFNR = t_lifnr .

  • How to re-index a modified query?

    Hi community,
    Due to a change to a BO I had also to adjust a already created query used to support an advanced search pane.
    Now every time I open my OWL, the OWL is empty and a message is raised saying "The index is temporary not available;index=.c016:1fs:jdx_zby003542_iptfrmv1yxsig7".
    Even though the message uses the word "temporary" this problem did not solve itself over time so I ask here:
    Is it possible/how can I force the re-indexing of a query?
    Best regards,
    Ludger

    Hi everyone
    This issue still persists in spite of my second message - i am pretty helpless.
    First I thought a clean solves the issue but it only prevents the "index temporary not available" message as long as no BO is present.
    As soon as a new BO is created, the situation occurs again.
    What can I do?

  • How to get fieldnames from Select * query ?

    How can I get the fieldnames returned with a SELECT * query ?
    When I use GetFieldName or GetFieldOriginalName I only get fieldnames of "*".

    You should use the fields collection, in the OraDynaset object.
    All you need to do is :
    for i = 0 to Recordset.Fields.Count -1
    debug.print Recordset.Fields(i).name
    debug.print Recordset.Fields(i).OriginalName 'this will print the field's name before an alias
    next i

  • How to get index of selected image??

    hi all
    I have a set of images that is displayed for the user and when he choose one image click on it and it will do sime action ... these images are stored in an array of images . How can i know the index of selected image ??

    i woul like to append an array of images in the screen and whenever i choose one of this images it link me to the class

  • How to include conditions in select query

    i want to write a select query wherein plants have to to be fetched from table vekp
    and if it is a plant then the  set movement type to 999 else leave for exiting.please help me on this

    >
    deep shikha wrote:
    > (This is module pool programming)
    what is modulepool programming doing in form printing forum.
    Please use appropriate forum next time.
    кu03B1ятu03B9к

  • How can we split a select query to 3 or 4 if it is fetching much records?

    I am running a query like:
    select * from table_name
    it will be fetching 152940696 records. Now i want to fetch this result as 3 or 4 select statements. That is, in the second query I want to fetch the records from where i stopped in the first query. and similar for the 3rd i have to continue from the 2nd query. And for the 4th query i have to start from where i have stopped in the 3rd query.
    when i tried with rownum we can fetch the records upto < or <= to a particular count like 100000000. But above this count i cannot fetch using rownum. Because > or >= wont work with rownum.
    Is there anyother way to split the select query as i explained.
    Thanks in advance

    I'll assume you want to split the query up for performance reasons.
    The easiest way to do this if you have the license is to use the parallel query option, which can help, hurt or do nothing. The only way to find out is to try. PQO would be best from a performance standpoint if possible, provided it will do what you need.
    Failing that as has been suggested you need a logical, scalable way to divide up the queries. It has already been pointed out that the rownum solution probably will not work correctly. Also, the MINUS with ROWNUM idea has the disadvantage of having to read a lot of the same data twice, making the query run longer.
    Perhaps a range would provide a way to split up the data - something like
    select whatever
      from table
    where primary_key < 10000000;
    select whatever
      from table
    where primary key between 10000001 and 199999999;
    ...

  • How to do outer join select query for an APEX report

    Hello everyone,
    I am Ann.
    I have one select statement that calculate the statistics for one month(October 2012 in this example)
    select ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE('Oct 2012','MON YYYY'))
    THEN last_day(TO_DATE('Oct 2012','MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by rollup(phase_number)
    Result is as below
    Phase_Number     AVG_DAYS
    Phase One     8.6666666666666667
    Phase Two     14.6
    Phase Three     12
         11.4615365
    I have other select list mainly list the months between two date value.
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )
    Query result is as below
    DISPLAY_MONTH
    AUG 2012
    SEP 2012
    OCT 2012
    Is there any way that I can join these two select statement above to generate a result like:
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Sep 2012     Phase One     7.66
    Oct 2012     Phase One     5.66
    Aug 2012     Phase Two     8.666
    Sep 2012     Phase Two     7.66
    Oct 2012     Phase Two     5.66
    Aug 2012     Phase Three     8.666
    Sep 2012     Phase Three     7.66
    Oct 2012     Phase Three     5.66
    Or
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Aug 2012     Phase Two     7.66
    Aug 2012     Phase Three     5.66
    Sep 2012     Phase One     8.666
    Sep 2012     Phase Two     7.66
    Sep 2012     Phase Three     5.66
    Oct 2012     Phase One     8.666
    Oct 2012     Phase Two     7.66
    Oct 2012     Phase Three     5.66
    And it can be order by either Phase Number or Month.
    My other colleague suggest I should use an left outer join but after trying so many ways, I am still stuck.
    One of the select I tried is
    select a.display_month,b.* from (
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )) a left outer join
    ( select to_char(ph.date_finished,'MON YYYY') as join_month, ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(a.display_month,'MON YYYY'))
    THEN last_day(TO_DATE(a.display_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE(a.display_month,'MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by to_char(ph.date_finished,'MON YYYY') , rollup(phase_number)) b
    on a.display_month = b.join_month
    but then I get an error
    SQL Error: ORA-00904: "A"."DISPLAY_MONTH": invalid identifier
    I need to display a report on APEX with option for people to download at least CSV format.
    I already have 1 inteactive report in the page, so don’t think can add another interactive report without using the iframe trick.
    If any of you have any ideas, please help.
    Thanks a lot.
    Ann

    First of all, a huge thanks for following this Frank.
    I have just started working here, I think the Oracle version is 11g, but not sure.
    To run Oracle APEX version 4, I think they must have at least 10g R2.
    This report is a bit challenging for me.I has never worked with PARTITION before.
    About the select query you suggested, I run , and it seems working fine, but if I try this,
    it return error ORA-01843: not a valid month
    DEFINE startmonth = "Aug 2012";
    DEFINE endmonth   = "Oct 2012";
    WITH     all_months     AS
         select add_months(to_date('&startmonth','MON YYYY'), rownum-1) AS which_month
         ,      add_months(to_date('&startmonth','MON YYYY'), rownum  ) AS next_month
         from all_objects
         where
         rownum <= months_between(to_date('&endmonth','MON YYYY'), add_months(to_date('&startmonth','MON YYYY'), -1))
    select TO_CHAR (am.which_month, 'Mon YYYY')     AS month
    ,      ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(am.which_month,'MON YYYY'))
    THEN last_day(TO_DATE(am.which_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    FROM           all_months          am
    LEFT OUTER JOIN  phase_membership  ph  PARTITION BY (ph.phase_number)
                                        ON  am.which_month <= ph.date_started
                               AND am.next_month  >  ph.date_started
                               AND ph.date_started <= last_day(TO_DATE(am.which_month,'MON YYYY'))  -- May not be needed
                               AND ph.active = 1
    LEFT OUTER join  court_engagement  ce  on  ph.mpm_eng_id = ce.engagement_id
                                        and ce.court_name IS NOT NULL  -- or something involving LIKE
    LEFT OUTER join  defendant         def on  ce.defendant_id = def.def_id
                                        AND def.active = 1
    group by rollup(phase_number, am.which_month)
    ORDER BY  am.which_month
    ,            ph.phase_number
    ;Here is the shorted versions of the three tables:
    A_DEFENDANT, A_ENGAGEMENT, A_PHASE_MEMBERSHIP
    CREATE TABLE "A_DEFENDANT"
        "DEF_ID"     NUMBER NOT NULL ENABLE,
        "FIRST_NAME" VARCHAR2(50 BYTE),
        "SURNAME"    VARCHAR2(20 BYTE) NOT NULL ENABLE,
        "DOB" DATE NOT NULL ENABLE,
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_DEFENDANT_PK" PRIMARY KEY ("DEF_ID"))
    Sample Data
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (101,'Joe','Bloggs',to_date('12/12/99','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (102,'John','Smith',to_date('20/05/00','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (103,'Jane','Black',to_date('15/02/98','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (104,'Minnie','Mouse',to_date('13/12/88','DD/MM/RR'),0);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (105,'Daisy','Duck',to_date('05/08/00','DD/MM/RR'),1);
    CREATE TABLE "A_ENGAGEMENT"
        "ENGAGEMENT_ID" NUMBER NOT NULL ENABLE,
        "COURT_NAME"    VARCHAR2(50 BYTE) NOT NULL ENABLE,
        "DATE_REFERRED" DATE,
        "DETERMINATION_HEARING_DATE" DATE,
        "DATE_JOINED_COURT" DATE,
        "DATE_TREATMENT_STARTED" DATE,
        "DATE_TERMINATED" DATE,
        "TERMINATION_TYPE" VARCHAR2(50 BYTE),
        "ACTIVE"           NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        "DEFENDANT_ID"     NUMBER,
        CONSTRAINT "A_ENGAGEMENT_PK" PRIMARY KEY ("ENGAGEMENT_ID"))
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (1,'AA',to_date('12/08/12','DD/MM/RR'),null,to_date('12/08/12','DD/MM/RR'),null,null,null,1,101);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (2,'BB',to_date('01/09/12','DD/MM/RR'),null,to_date('02/09/12','DD/MM/RR'),null,null,null,1,102);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (3,'AA',to_date('02/09/12','DD/MM/RR'),null,to_date('15/09/12','DD/MM/RR'),null,null,null,1,103);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (4,'BB',to_date('01/10/12','DD/MM/RR'),null,to_date('02/10/12','DD/MM/RR'),null,null,null,1,105);
    CREATE TABLE "A_PHASE_MEMBERSHIP"
        "MPM_ID"       NUMBER NOT NULL ENABLE,
        "MPM_ENG_ID"   NUMBER NOT NULL ENABLE,
        "PHASE_NUMBER" VARCHAR2(50 BYTE),
        "DATE_STARTED" DATE NOT NULL ENABLE,
        "DATE_FINISHED" DATE,
        "NOTES"  VARCHAR2(2000 BYTE),
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_PHASE_MEMBERSHIP_PK" PRIMARY KEY ("MPM_ID"))
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (1,1,'PHASE ONE',to_date('15/09/12','DD/MM/RR'),to_date('20/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (2,1,'PHASE TWO',to_date('21/09/12','DD/MM/RR'),to_date('29/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (3,2,'PHASE ONE',to_date('12/09/12','DD/MM/RR'),null,null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (4,3,'PHASE ONE',to_date('20/09/12','DD/MM/RR'),to_date('01/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (5,3,'PHASE TWO',to_date('02/10/12','DD/MM/RR'),to_date('15/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (6,4,'PHASE ONE',to_date('03/10/12','DD/MM/RR'),to_date('10/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (7,3,'PHASE THREE',to_date('17/10/12','DD/MM/RR'),null,null,0);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (8,1,'PHASE THREE',to_date('30/09/12','DD/MM/RR'),to_date('16/10/12','DD/MM/RR'),null,1);
    The requirements are:
    The user must be able to request the extract for one or more calendar months, e.g.
    May 2013
    May 2013 – Sep 2013.
    The file must contain a separate row for each calendar month in the requested range. Each row must contain the statistics computed for that calendar month.
    The file must also include a row of totals.
    The user must be able to request the extract for either Waitakere or Auckland or Consolidated (both courts’ statistics accumulated).
    Then the part that I am stuck is
    For each monitoring phase:
    Phase name (e.g. “Phase One”)
    Avg_time_in_phase_all_particip
    for each phase name,
    Add up days in each “phase name” Monitoring Phase, calculated as:
    If Monitoring Phase.Date Finished is NULL or > month end date,
    +(*Month end date* Minus Monitoring Phase.Date Started Plus 1)+
    Otherwise (phase is complete)
    +(Monitoring Phase.Date Finished Minus Monitoring Phase.Date Started Plus 1.)+
    Divide by the numbers of all participants who have engaged in “phase name”.
    This is the words of the Business Analyst,
    I try to do as required but still struggle to identify end_month for the above formula to display for the range of months.
    Of course, I can write two nested cursor. The first one run the list of month, then for each month, run the parameterised report.
    But I prefer if possible just use SQL statements, or at least a PL/SQL but return a query.
    With this way, I can create an APEX report, and use their CSV Extract function.
    Yes, you are right, court_name is one of the selection parameters.
    And the statistics is not exactly for one month. It is kind of trying to identify all phases that are running through the specified month (even phase.date_started is before the month start).
    This is the reason why I put the condition AND ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY')) (otherwise I get negative avg_days)
    User can choose either one court "AA" or "BB" or combined which is all figures.
    Sorry for bombarding you a lot of information.
    Thanks a lot, again.
    Edited by: Ann586341 on Oct 29, 2012 9:57 PM
    Edited by: Ann586341 on Oct 29, 2012 9:59 PM

  • How to improve performance of select query when primary key is not referred

    Hi,
    There is a select query where we are unable to refrence primary key of the tables:
    Since, the the below code is refrensing to vgbel and vgpos fields instead of vbeln and posnr..... the performance is very  slow.
    select vbeln posnr into (wa-vbeln1, wa-posnr1)             
           from lips                                            
           where ( pstyv ne 'ZBAT'    
               and pstyv ne 'ZNLN' )  
               and vgbel = i_vbap-vbeln                         
               and vgpos = i_vbap-posnr.                        
    endselect.                                                 
    Please le t me know if you have some tips..

    hi,
    I hope you are using the select statement inside a loop ...endloop get that outside to improve the performance ..
    if not i_vbap[] is initial.
    select vbeln posnr into table it_lips
    from lips
    for all entries in  i_vbap
    where ( pstyv ne 'ZBAT'
    and pstyv ne 'ZNLN' )
    and vgbel = i_vbap-vbeln
    and vgpos = i_vbap-posnr.
    endif.

Maybe you are looking for