Help in modifying this query

Hi everyone,
In the below query, for the user_code column, if the same data is present in mst_user and unlock_user_checker tables, then only the data from the unlock_user_checker table must be displayed in the user code column.
Kindly help !!!
select a.user_name as usrname,
a.user_code as usrcode,
b.no_of_login_attempt as usrattempt,
a.user_status as usrstatus,
c.unlocked_by as usrunlockedby,
c.unlocked_on as usrunlockedon,
c.approved_by as usrapprovedby,
c.approved_on as usrapprovedon,
c.rem as usrremarks,
c.approve_status as usrapprovestatus
from mst_user a, user_log_info b, unlock_user_checker c
where (b.No_of_login_Attempt >= 2 or a.user_status = '1')
and a.user_code = b.user_code
and a.user_code = c.user_code

How about this ??
select da.acct_nr,
       smas.mrkt_id,
       smas.fld_sls_cmpgn_perd_id,
       smas.acct_key,
       smas.upln_acct_key,
       smas.awrd_sls_amt,
       smas.fld_net_sls_amt,
       smas.stf_ind,
       da1.acct_nr,
       smas.fld_sls_cmpgn_perd_id,
       smas.acct_key,
       smas.upln_acct_key,
       smas.awrd_sls_amt,
       smas.fld_net_sls_amt,
       smas.stf_ind,
       da1.acct_nr,
       prev.*
  From cdw.sum_mrkt_acct_sls smas
  join codi.dim_acct da on (smas.mrkt_id = da.mrkt_id and
                           smas.acct_key = da.acct_key)
  join codi.dim_acct da1 on (smas.mrkt_id = da1.mrkt_id and
                            smas.UPLN_acct_key = da1.ACCT_KEY)
where smas.acct_key in (select dwnln_acct_key
                           from codi.dim_ldrshp_genlgy
                          where mrkt_id = 66
                            and fld_sls_cmpgn_perd_id in( 20100304,20100305,20100306)
                            and root_upln_acct_key =
                                (select acct_key
                                   from codi.dim_acct
                                  where acct_nr = '0032622'
                                    and mrkt_id = 66))
   and smas.mrkt_id = 66
   and smas.fld_sls_cmpgn_perd_id in( 20100304,20100305,20100306)
   and smas.sls_org_key - 100
order by 1

Similar Messages

  • Help to modify this query

    -- i am using oracle 10g express edition
    when using this one
    select student_courses.student_id , student_courses.grade
    from courses
    left outer join student_courses
    ON student_courses.course_id = courses.course_id
    where COURSE_TARGET_DEPT_ID = 1 and student_courses.student_id = 1
    20 rows returned which are the courses student # 1 had .
    when using
    select student_courses.student_id , student_courses.grade
    from courses
    left outer join student_courses
    ON student_courses.course_id = courses.course_id
    where COURSE_TARGET_DEPT_ID = 1
    it returns all the courses of that department by all students ...
    what i want is returning the courses and grades for a certain student in that department .
    i.e" selecting the courses he didnt have is my problem + the ones he had "

    It sounds like you want a list of the courses in one department and to identify which of those courses an individual student is enrolled in. This may help;
    CREATE TABLE student_courses AS (
       SELECT 1 student_id, 10 course_id, 'B' grade FROM dual);
    Table created
    CREATE TABLE courses AS (
       SELECT 10 course_id, 1 course_target_dept_id, 'Pub Crawling' course_name FROM dual UNION ALL
       SELECT 20, 1, 'Spring Breaking' FROM dual UNION ALL
       SELECT 40, 2, 'Basket Weaving' FROM dual);
    Table created
    SELECT c.course_target_dept_id, c.course_name, sc.student_id, sc.grade
    FROM courses c
    LEFT OUTER JOIN student_courses sc
    ON sc.course_id = c.course_id
    WHERE course_target_dept_id = 1
    AND (sc.student_id = 1
    OR sc.course_id IS NULL);
    COURSE_TARGET_DEPT_ID COURSE_NAME     STUDENT_ID GRADE
                        1 Pub Crawling             1 B
                        1 Spring Breaking           

  • How to modify this query to get the desired output format

    I hv written a Query to display all the parent table names and their primary key columns(relevant to this foreign key of the child table).The query is given below...
    SELECT DISTINCT(TABLE_NAME) AS PARENT_TABLE,COLUMN_NAME AS PARENT_COLUMN
    FROM ALL_CONS_COLUMNS
    WHERE CONSTRAINT_NAME IN (SELECT AC.R_CONSTRAINT_NAME
    FROM ALL_CONSTRAINTS AC
    WHERE AC.TABLE_NAME=TABLE_NAME
    AND AC.TABLE_NAME='&TABLE'
    AND AC.R_CONSTRAINT_NAME IS NOT NULL);
    This query will display all the parent tables and their primary key columns.Now my problem is that how to modify this query to also display the foreign key column name of the child table.
    I want the query result in the following format.The query should display the following columns.1)child table's name,2)child table's foreign key column name,3)the corresponding parent table's name,4)the parent table's primary key column name(which is the foreign key in the child table).
    For Example I want the output as follows...
    TAKE THE CASE OF SCOTT.EMP(AS INPUT TO YOUR QUERY)
    CHILD_TABLE CHILD_COLUMN PARENT_TABLE PARENT_COLUMN
    EMP DEPTNO DEPT DEPTNO
    In this result I hv used alias name for the columns.The query should display this only for the foreign keys in the child table.In the query which I sent to you earlier will give the parent table and the parent column names,But I also want to append the child table and child column names there.
    any help on how to tackle would be appreciated.

    Try this query
    SELECT c.table_name child_table,
         c.column_name child_column,
         p.table_name parent_table,
         p.column_name parent_column
    FROM user_constraints a,user_constraints b,user_cons_columns c,
         user_cons_columns p
    WHERE a.r_constraint_name=b.constraint_name and
          a.constraint_name=c.constraint_name and
          b.constraint_name=p.constraint_name and
          c.position=p.position
    ORDER BY c.constraint_name,c.position
    Anwar

  • HELP TO TUNE THIS QUERY

    Hi,
    I'm using below query in procedure.It's taking more more time can some one help to tune this query or advice to rewrite the query.
    Databse :10.1
    SELECT   'Reading Comprehension' TEST_NAME,T.TEST_END_DATE TEST_SESSION_DATE,
            C.POOL_VERSION_ID, I.CREATED_ON POOL_CREATED_DT,
            C.ITEM_ID, C.ITEM_RESPONSE_ID, S.STUDENT_ID_PK, C.RESPONSE_KEY, C.IS_CORRECT RESPONSE_IS_CORRECT,
            T.SCORE SCALE_SCORE, C.RESPONSE_DURATION, P.ITEM_KEY,
            T.TEST_SESSION_DETAIL_ID, SYSDATE CREATED_ON
           -- BULK COLLECT INTO TV_PSYCHO_DET
            FROM
            CAT_ITEM_PARAMETER P, CAT_ITEM_USER_RESPONSE C, TEST_SESSION_DETAIL T,
            TEST_SESSION S, ITEM_POOL_VERSION I, TEST_DETAIL D
            ,INSTITUTION E
            WHERE  TRUNC(T.TEST_END_DATE) BETWEEN TO_DATE('01-11-09','dd-mm-yy') AND TO_DATE('30-11-09','dd-mm-yy')
            AND D.TEST_NAME =  'Reading Comprehension'
            AND T.TEST_SESSION_STATUS_ID = 3
            AND I.POOL_AVAILABILITY='Y'
            AND P.PRETEST=0 AND C.RESTART_FLAG=0
            AND T.TEST_DETAIL_ID = D.TEST_DETAIL_ID
            AND S.TEST_SESSION_ID = T.TEST_SESSION_ID
            AND C.TEST_SESSION_DETAIL_ID = T.TEST_SESSION_DETAIL_ID
            AND S.INSTITUTION_ID=E.INSTITUTION_ID
            AND SUBSTR(E.INSTITUTION_ID_DISPLAY,8,3) <> '000'
            AND I.ITEM_ID = C.ITEM_ID
            AND P.ITEM_ID = I.ITEM_ID;expln plan
    Plan hash value: 3712814491                                                                                                      
    | Id  | Operation                                 | Name                        | Rows  | Bytes | Cost (%CPU)| Time     | Pstart|
    Pstop |                                                                                                                          
    |   0 | SELECT STATEMENT                          |                             | 50857 |  7151K| 93382   (1)| 00:18:41 |       |
          |                                                                                                                          
    |*  1 |  FILTER                                   |                             |       |       |            |          |       |
          |                                                                                                                          
    |*  2 |   HASH JOIN                               |                             | 50857 |  7151K| 93382   (1)| 00:18:41 |       |
          |                                                                                                                          
    |   3 |    PARTITION HASH ALL                     |                             |  2312 | 23120 |    25   (0)| 00:00:01 |     1 |
        5 |                                                                                                                          
    |*  4 |     TABLE ACCESS FULL                     | CAT_ITEM_PARAMETER          |  2312 | 23120 |    25   (0)| 00:00:01 |     1 |
        5 |                                                                                                                          
    |*  5 |    HASH JOIN                              |                             | 94938 |    12M| 93356   (1)| 00:18:41 |       |
          |                                                                                                                          
    |*  6 |     TABLE ACCESS FULL                     | ITEM_POOL_VERSION           |  9036 |   132K|    30   (0)| 00:00:01 |       |
          |                                                                                                                          
    |*  7 |     TABLE ACCESS BY GLOBAL INDEX ROWID    | CAT_ITEM_USER_RESPONSE      |     9 |   279 |    18   (0)| 00:00:01 | ROWID |
    ROWID |                                                                                                                          
    |   8 |      NESTED LOOPS                         |                             | 45349 |  5270K| 93325   (1)| 00:18:40 |       |
          |                                                                                                                          
    |*  9 |       HASH JOIN                           |                             |  4923 |   423K| 11377   (1)| 00:02:17 |       |
          |                                                                                                                          
    |* 10 |        INDEX FAST FULL SCAN               | INSTI_ID_NAME_COUN_DISP_IDX |  8165 |   111K|    18   (0)| 00:00:01 |       |
          |                                                                                                                          
    |* 11 |        HASH JOIN                          |                             |  4923 |   355K| 11359   (1)| 00:02:17 |       |
          |                                                                                                                          
    |* 12 |         TABLE ACCESS BY GLOBAL INDEX ROWID| TEST_SESSION_DETAIL         |  4107 |   148K|  6804   (1)| 00:01:22 | ROWID |
    ROWID |                                                                                                                          
    |  13 |          NESTED LOOPS                     |                             |  4923 |   278K|  6806   (1)| 00:01:22 |       |
          |                                                                                                                          
    |* 14 |           INDEX RANGE SCAN                | TEST_DETAIL_AK_1            |     1 |    21 |     2   (0)| 00:00:01 |       |
          |                                                                                                                          
    |* 15 |           INDEX RANGE SCAN                | TEST_SESSION_DETAIL_FK2_I   | 39737 |       |   102   (0)| 00:00:02 |       |
          |                                                                                                                          
    |  16 |         PARTITION HASH ALL                |                             |  1672K|    25M|  4546   (1)| 00:00:55 |     1 |
        5 |                                                                                                                          
    |  17 |          TABLE ACCESS FULL                | TEST_SESSION                |  1672K|    25M|  4546   (1)| 00:00:55 |     1 |
        5 |                                                                                                                          
    |* 18 |       INDEX RANGE SCAN                    | CAT_ITEM_USER_RESP_IDX1     |    18 |       |     3   (0)| 00:00:01 |       |
          |                                                                                                                          
    Predicate Information (identified by operation id):                                                                              
       1 - filter(TO_DATE('01-11-09','dd-mm-yy')<=TO_DATE('30-11-09','dd-mm-yy'))                                                    
       2 - access("P"."ITEM_ID"="I"."ITEM_ID")                                                                                       
       4 - filter("P"."PRETEST"=0)                                                                                                   
       5 - access("I"."ITEM_ID"="C"."ITEM_ID")                                                                                       
       6 - filter("I"."POOL_AVAILABILITY"='Y')                                                                                       
       7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0)                                                                                   
       9 - access("S"."INSTITUTION_ID"="E"."INSTITUTION_ID")                                                                         
      10 - filter(SUBSTR("E"."INSTITUTION_ID_DISPLAY",8,3)<>'000')                                                                   
      11 - access("S"."TEST_SESSION_ID"="T"."TEST_SESSION_ID")                                                                       
      12 - filter(TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))>=TO_DATE('01-11-09','dd-mm-yy') AND "T"."TEST_SESSION_STATUS_ID"=3   
                  AND TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))<=TO_DATE('30-11-09','dd-mm-yy'))                                 
      14 - access("D"."TEST_NAME"='Reading Comprehension')                                                                           
      15 - access("T"."TEST_DETAIL_ID"="D"."TEST_DETAIL_ID")                                                                         
      18 - access("C"."TEST_SESSION_DETAIL_ID"="T"."TEST_SESSION_DETAIL_ID")                                                         
    43 rows selected.Edited by: user575115 on Dec 18, 2009 12:31 AM

    When you see something like ...
       7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0)                                                                                    It means that Oracle had to do a conversion for you since you aren't using the proper data type in your query.
    That would mean IF there is an index on that column, it won't be useable...

  • Help to Simplify this query

    i am using
    Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production
    With the Partitioning option
    JServer Release 8.1.7.4.0 - Production
    Please help to simplify this query. I also want to make this as a procedure.
    select
    RH.resort as RH_RESORT,
    RH.rate_code as RH_RATE_CODE,
    RD.rate_detail_id as RD_RATE_DETAIL_ID,
    RD.rate1 as RD_RATE1,
    RD.rate2 as RD_RATE2,
    RD.rate3 as RD_RATE3,
    RD.rate4 as RD_RATE4,
    RD.rate5 as RD_RATE5,
    RRC.room_category as RM_CAT,
    initcap(RRMCAT.long_description) as RM_DESC,
    RH.DAY1,
    RH.DAY2,
    RH.DAY3,
    RH.DAY4,
    RH.DAY5,
    RH.DAY6,
    RH.DAY7,
    RH.WEEKEND1,
    RH.WEEKEND2,
    RH.WEEKEND3,
    RH.WEEKEND4,
    RH.WEEKEND5,
    RH.WEEKEND6,
    RH.WEEKEND7
    from pms_rate_header RH,
    pms_rate_detail RD,
    pms_rate_room_cat RRC,
    resort_room_category RRMCAT
    where RH.inactive_date is NULL
    and RH.RESORT='FABGOI'
    and RH.RATE_CODE ='CRRRACK'
    and ('15-Jan-2007' >= RH.BEGIN_DATE
    and '16-Jan-2007' <= RH.END_DATE)
    and RD.rate_header_id=RH.rate_header_id
    and RD.inactive_date is NULL
    and ('15-Jan-2007' >= RD.BEGIN_DATE
    and '16-Jan-2007' <= RD.END_DATE)
    and RRC.rate_detail_id=RD.rate_detail_id
    and RRC.resort=RH.resort
    and RRMCAT.resort=RH.resort
    and RRMCAT.room_category=RRC.room_category
    and RRC.inactive_date is NULL
    and RRMCAT.inactive_date IS NULL
    regards
    lee1212

    where RH.inactive_date is NULL
    and RH.RESORT='FABGOI'
    and RH.RATE_CODE ='CRRRACK'
    and ('15-Jan-2007' >= RH.BEGIN_DATE
    and '16-Jan-2007' <= RH.END_DATE)
    and RD.rate_header_id=RH.rate_header_id
    and RD.inactive_date is NULL
    and ('15-Jan-2007' >= RD.BEGIN_DATE
    and '16-Jan-2007' <= RD.END_DATE)
    and RRC.rate_detail_id=RD.rate_detail_id
    and RRC.resort=RH.resort
    and RRMCAT.resort=RH.resort
    and RRMCAT.room_category=RRC.room_category
    and RRC.inactive_date is NULL
    and RRMCAT.inactive_date IS NULL
    in the above part i am finding repeated joins and lot of 'and's
    i want to know any line can be eliminated or the the query can be rewritten in a simple way without affecting it's accuracy?
    regards
    Lee1212

  • Plz help me design this query

    Hi,
    Can you’ll please help me with this query.
    Here is a little bit of background:
    One title can have multiple items associated with it.
    Table: TITLE has the master list of titles. TITLE_ID is the primary key.
    Table: ITEM has the master list of all items. ITEM_ID is the primary. This table also has the TITLE_ID which stores title for this item.
    Table: ITEM_STATUS has fields ITEM_ID and STATUS_ID. This field contains statuses for items. But not all items contained in the table ITEM are in this table.
    I want to find TITLE_ID’s whose all items (all ITEM_ID in table ITEM having same value for TITLE_ID) have a particular status (for example STATUS_ID = 2) in table ITEM_STATUS.
    Let’s say TITLE_ID = 1 has 5 items in table ITEM_ID and only 4 items out of it in table ITEM_STATUS with STATUS_ID = 2, then this TITLE_ID should not come. OR
    Let’s say TITLE_ID = 1 has 5 items in table ITEM_ID and all these 5 items are in table ITEM_STATUS but only 1 has STATUS_ID = 2, then this TITLE_ID should also not come
    In the above case only if all 5 items are contained in table ITEM_STATUS have STATUS_ID = 2 then this TITLE_ID should be reported by the query.
    What should be the query like for this one, I am fairly new to SQL so plz guide me.
    Thank you,
    Raja

    I haven't tested the query below. Try it and let me know for any issues:
    SELECT     DISTINCT t.title_id
         FROM     title t,
                        item i,
                        item_status its
    WHERE     t.title_id = i.title_id
         AND     i.item_id = its.item_id
         AND     NOT EXISTS     (
                                                           SELECT 1
                                                                FROM item_status its1
                                                           WHERE its1.item_id = i.item_id
                                                                AND status_id <> 'YOUR_ITEM_STATUS'
                                                      )

  • Please help to modifiy this query for better performance

    Please help to rewrite this query for better performance. This is taking long time to execute.
    Table t_t_bil_bil_cycle_change contains 1200000 rows and table t_acctnumberTab countains  200000 rows.
    I have created index on ACCOUNT_ID
    Query is shown below
    update rbabu.t_t_bil_bil_cycle_change a
       set account_number =
           ( select distinct b.account_number
             from rbabu.t_acctnumberTab b
             where a.account_id = b.account_id
    Table structure  is shown below
    SQL> DESC t_acctnumberTab;
    Name           Type         Nullable Default Comments
    ACCOUNT_ID     NUMBER(10)                            
    ACCOUNT_NUMBER VARCHAR2(24)
    SQL> DESC t_t_bil_bil_cycle_change;
    Name                    Type         Nullable Default Comments
    ACCOUNT_ID              NUMBER(10)                            
    ACCOUNT_NUMBER          VARCHAR2(24) Y    

    Ishan's solution is good. I would avoid updating rows which already have the right value - it's a waste of time.
    You should have a UNIQUE or PRIMARY KEY constraint on t_acctnumberTab.account_id
    merge rbabu.t_t_bil_bil_cycle_change a
    using
          ( select distinct account_number, account_id
      from  rbabu.t_acctnumberTab
          ) t
    on    ( a.account_id = b.account_id
           and decode(a.account_number, b.account_number, 0, 1) = 1
    when matched then
      update set a.account_number = b.account_number

  • Could you please help me make this query less complicated

    could you please help me make this query less complicated
    select t1.R_OBJECT_ID
    from dm_relation_sp a, ddt_resolution_sp t1
    where a.parent_id = '0900000283560456' -----------ID
    and a.child_id = t1.R_OBJECT_ID
    union all
    select t3.R_OBJECT_ID
    from ddt_resolution_sp t3
    where t3.R_OBJECT_ID in (select t2.child_id
    from dm_relation_sp t2
    where t2.parent_id in (select a.child_id
    from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
    where a.parent_id = '0900000283560456' -----------ID
    and a.child_id = t1.R_OBJECT_ID))
    union all
    select t4.R_OBJECT_ID
    from ddt_resolution_sp t4
    where t4.R_OBJECT_ID in(
    select t3.child_id from dm_relation_sp t3
    where t3.parent_id in (
    select t2.child_id
    from asud_fsk.dm_relation_sp t2
    where t2.parent_id in (select a.child_id
    from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
    where a.parent_id = '0900000283560456' -----------ID
    and a.child_id = t1.R_OBJECT_ID))
    and t3.relation_name = 'RESOLUTION_RELATION')
    union all
    select t5.R_OBJECT_ID
    from ddt_resolution_sp t5
    where t5.R_OBJECT_ID in
    (select t4.child_id
    from dm_relation_sp t4
    where t4.parent_id in(
    select t3.child_id from dm_relation_sp t3
    where t3.parent_id in (
    select t2.child_id
    from asud_fsk.dm_relation_sp t2
    where t2.parent_id in (select a.child_id
    from asud_fsk.dm_relation_sp a, asud_fsk.ddt_resolution_sp t1
    where a.parent_id = '0900000283560456' -----------ID
    and a.child_id = t1.R_OBJECT_ID))
    and t3.relation_name = 'RESOLUTION_RELATION')
    and t4.relation_name = 'RESOLUTION_RELATION')
    Edited by: user13025450 on 29.04.2010 16:23

    Hi,
    Welcome to the forum! You'll find that there are many qualified people (such as Tubby) willing to help you. Will you do what you can to help them? In order to simplify the query you posted,someone will first have to understand what it does, what the tables that it uses are like, and what tools you have to work with (that is, what version of Oracle, and any other software you are using). To actually test their ideas, people will need versions of your tables.
    Many people, if they spent enough time, might be able to figure out roughly what you are doing, make some tables themselves and test a solution. You can help with all of that. I assume you already know what the appliction is, and what this particular query is supposed to do: you don't have to figure out any of that, you just have to say it. You know what all your tables are, what the datatypes of all the columns are, and what kinds of data are in the tables: you don't have to guess at any of that.
    Describe what you're doing. Think about it: how do we know that
    SELECT  NULL
    FROM    dual;doesn't do what you want?
    Post CREATE TABLE and INSERT statements for a little sample data.
    Post the results that this query is supposed to produce from those results. (Is it producing the right output now? Then it should be easy to post the correct results.)
    Describe, as well as you can, how the present query is doing it.
    Format your existing code, so it's easy to see what the different branches of the UNION are, and what the main clauses are in each one.
    When posting formatted text (code or results) type these 6 characters
    \(all small letters, inside curly brackets) before and after each formatted section, to keep this site from compressing the spaces.
    Say what versions of Oracle (e.g. 10.2.0.3.0) and any other relevant software you are using.
    I know it's a lot of work, but it really helps. You can do it as well (probably better) than anyone else, and if you're unwilling to do it, why should anyone else be willing?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Query Issue in Creating a View....Please help me with this query..

    I would like to create a view on this table with four columns
    1. PN#_EXP_DATE
    2. PN#
    3. PN#_EFF_DATE
    4. PN#
    P_S_C     A_C     P     EXP_DT
    21698     13921     1     5/29/2009 3:15:41 PM     
    21698     13921     1     5/29/2009 3:54:57 PM     
    21698     1716656     4     5/29/2009 3:15:41 PM     
    21698     3217     3     5/29/2009 3:15:40 PM     
    21698     3217     3     5/29/2009 3:54:57 PM     
    21698     60559     2     5/29/2009 3:15:41 PM     
    21698     60559     2     5/29/2009 3:54:57 PM     
    I have a trigger on A, which inserts the DML records into B. (Table A and B structure is the almost the same,
                                       where table B will have one extra column exp_dt)
    NOw Table B can have records with same P_S_C and A_C columns and exp_dt will capture the history.
    for example: from the above sample data, let us take first two records..
    P_S_C     A_C     P     EXP_DT
    21698     13921     1     5/29/2009 3:15:41 PM     --- Record 1
    21698     13921     1     5/29/2009 3:54:57 PM     --- Record 2
    from this..
    Note: 1. Table A and Table C can be joined using A.P_S_C and C.R_C to get the start_date.
    2. PN# comes from table D. It contains numbers for the resp. weeks.
    3. PN#_EFF_DATE is the previous immediate previous date for that record in history table (Table B).
    I wanted the data like..
    ---- this is for the second record in the above..
    PN#_EXP_DATE PN# PN#_EFF_DATE PN#
    5/29/2009 3:54:57 PM     214 5/29/2009 3:15:41 PM     214
    ---- this is for the first record in the above..
    PN#_EXP_DATE PN# PN#_EFF_DATE PN#
    5/29/2009 3:54:41 PM     214 ( for this we should query the table C to get the
                        start_date, for this combinatation of P_S_C and A_C in table B
                             where B.P_S_C = C.A_C
                             and that value should be the EFF_DT for this record)
    Please help me with this....
    Thanks in advance..

    Hi All,
    select d.P# as "PN#_EXP_DATE", exp_date
    from daily_prd d, cbs1_assoc_hist b
    where to_char(d.day_date,'MM/DD/YYYY') = to_char(b.exp_date,'MM/DD/YYYY')
    and d.period_type = 'TIMEREPORT';
    This above query gives the output as follows:
    pn#_exp_date exp_date
    214     5/29/2009 3:15:40 PM
    214     5/29/2009 3:15:41 PM
    214          5/29/2009 3:15:41 PM
    214          5/29/2009 3:15:41 PM
    214          5/29/2009 3:54:57 PM
    214          5/29/2009 3:54:57 PM
    214          5/29/2009 3:54:57 PM
    This below is the data from history table (Table B).
    P_S_C     A_C PLACE EXP_DATE
    21698          3217          3     5/29/2009 3:15:40 PM     
    21698          13921          1     5/29/2009 3:15:41 PM     
    21698          1716656          4     5/29/2009 3:15:41 PM     
    21698          60559          2     5/29/2009 3:15:41 PM     
    21698          13921          1     5/29/2009 3:54:57 PM     
    21698          3217          3     5/29/2009 3:54:57 PM     
    21698          60559          2     5/29/2009 3:54:57 PM     
    I got the pn#_exp_date from the Table 'D', for the given exp_date from Table B.
    My question is again....
    CASE - 1
    from the given records above, I need to look for exp_date for the given same P_S_C and A_C.
    in this case we can take the example...
    P_S_C     A_C PLACE EXP_DATE
    21698          3217          3     5/29/2009 3:15:40 PM
    21698          3217          3     5/29/2009 3:54:57 PM
    In this case, the
    pn#_exp_date exp_date     pn#_eff_date eff_date
    214     5/29/2009 3:15:57 PM     < PN# corresponding to the     5/29/2009 3:15:40 PM
                        eff_date .>
                        <Basically the eff_date is
                        nothing but the exp_date only.
                        we should take the immediate before one.
    In this case, our eff_date is '5/29/2009 3:15:40 PM'.
    but how to get this.
    CASE - 2
    from the above sample data, consider this
    P_S_C     A_C PLACE EXP_DATE
    21698     1716656     4     5/29/2009 3:15:41 PM
    In this case, there is only one record for the P_S_C and A_C combination.
    The expected result :
    pn#_exp_date exp_date               pn#_eff_date eff_date
    214     5/29/2009 3:15:41 PM     < PN# corresponding to the     5/29/2009 3:15:40 PM
                        eff_date .>
                   <Basically the eff_date is
                   nothing but the exp_date only.
                        we should take the immediate before one.
    In this case to get the eff_date, we should query the Table 'C', to get the eff_date, which is START_DT column in this table.
    for this join B.P_S_C and C.R_C.
    Hope I am clear now..
    Thanks in advance.....

  • Help in Tuning this Query

    Hi,
    I have a query in my proj where the same table is looked up twice in the same query.
    Can anybody suggest in improving the performance of this query?
    select * from table1 a1 where (a1.column1, a1.column2, a1.column3, a1.column4, a1.column5, a1.column6, a1.column7, a1.column8, a1.column9,
    a1.column10) in ( select a2.column1, a2.column2, a2.column3, a2.column4, a2.column5, a2.column6, a2.column7, a2.column8, a2.column9,
    a2.column10 from table1 a2 where column20 = '<condn>')
    The table1 used here is same in outer query as well as the sub query. this is a example of what we use here, and the table1 contains 30 million rows. Though, creating index with 10 columns can be a option, we already have a unique index with 11 columns(which includes 10 from this query) and will that be helpful in anyway? or the same existing index can be forced?
    Thanks a lot for ur time

    Depending on the selectivity of column20 I am not sure Index is the best way to go. It might perform better with two full scans and a hash-join.
    Anyway, I do prefer the syntax:
    select /*+ leading(a2) */ a1.*
    from table1 a1, table1 a2
    where a2.column20 = '<condn>'
    and a1.column1 = a2.column1
    and a1.column2 = a2.column2
    and  a1.column3 = a2.column3
    and  a1.column4 = a2.column4
    and  a1.column5 = a2.column5
    and  a1.column6 = a2.column6
    and  a1.column7 = a2.column7
    and  a1.column8 = a2.column8
    and  a1.column9 = a2.column9
    and  a1.column10 = a2.column10;I've added a leading hint to tell oracle that the start table is a2. Might be useless.
    Ensure your stats are up to date. You might need histograms here if your column20 is skewed.
    Hope this helps,
    François
    Edited by: Francois Berger on Oct 24, 2008 1:47 AM

  • Help on tuning this query

    Hi all i have this query:
    SELECT VTA.CO_VENDEDOR
    ,VTA.NB_VENDEDOR
    ,VTA.CO_CLASE_CLIENTE
    ,VTA.DE_CLASE_CLIENTE
    ,VTA.CO_CLIENTE
    ,VTA.NB_CLIENTE
    ,VTA.MN_VENDIDO
    ,NVL(DEV.MN_DEVUELTO,0) MN_DEVUELTO
    ,VTA.MN_VENDIDO - NVL(DEV.MN_DEVUELTO,0) MN_NETO_VENDIDO
    ,NVL(COB.MN_COBRADO,0) MN_COBRADO
    ,NVL(COB.MN_DESCUENTO,0) MN_DESCUENTO
    ,NVL(COB.MN_COBRADO,0) + NVL(COB.MN_DESCUENTO,0) MN_COBRADO_MAS_DESCUENTO
    FROM (SELECT FCL.CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
    ,FCL.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
    ,FCL.CO_ORGANIZACION CO_CLIENTE
    ,FCL.ORG_NB_CLIENTE NB_CLIENTE
    ,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
    ,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
    ,SUM((CA_PRODUCTO * (PR_PRODUCTO - NVL(PR_DESCUENTO_PRODUCTO,0))) * (1 - NVL(PC_DESCUENTO,0))) MN_VENDIDO
    FROM S04_FACTURA_CLIENTE_TOTAL_R FCL
    ,S04_FACTURA_CLIENTE_PRD_TOT FPR
         ,(SELECT FCP.FAC_ID_FACTURA
    ,SUM(DDC.MN_DEBITO_CREDITO) /
    SUM(FCP.CA_PRODUCTO * (FCP.PR_PRODUCTO - NVL(FCP.PR_DESCUENTO_PRODUCTO,0))) PC_DESCUENTO
         FROM S04_DOCUMENTO_DEBITO_CREDITO_R DDC
    ,S04_FACTURA_CLIENTE_PRD_TOT FCP
         WHERE DDC.ID_DOCUMENTO_REFERENCIA = FCP.FAC_ID_FACTURA
    AND DDC.TDC_IN_DEBITO_CREDITO = 'C'
    GROUP BY FCP.FAC_ID_FACTURA) DCT
    WHERE FCL.ID_REGISTRO = FPR.FAC_ID_FACTURA
    AND DCT.FAC_ID_FACTURA (+) = FPR.FAC_ID_FACTURA
    AND FCL.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
    AND FCL.ORG_ID_CLIENTE = NVL(NULL,FCL.ORG_ID_CLIENTE)
    AND FCL.PER_ID_VENDEDOR = NVL(7647771,FCL.PER_ID_VENDEDOR)
                   AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
    AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
    FROM S00_UBICACION_GEOGRAFICA
    START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
    CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
    GROUP BY FCL.CTV_CO_CLASE_ORGANIZACION
    ,FCL.CTV_DE_CLASE_ORGANIZACION
    ,FCL.CO_ORGANIZACION
    ,FCL.ORG_NB_CLIENTE
    ,PER_CO_IDENTIFICACION_VENDEDOR
    ,PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    PER_NB_PRIMER_APELLIDO_VEND) VTA
    ,(SELECT NDC .CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
    ,NDC.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
    ,NDC.CO_CLIENTE
    ,NDC.ORG_NB_CLIENTE NB_CLIENTE
    ,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
    ,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
    ,SUM(CA_PRODUCTO * (PR_PRODUCTO - NVL(PR_DESCUENTO_PRODUCTO,0))) MN_DEVUELTO
    FROM S06_NOTA_DEBITO_CREDITO_TOT_R NDC
         ,S06_DETALLE_NOTA_DEB_CRED_TOT DND
    ,S04_FACTURA_CLIENTE_TOTAL_R FCL
         WHERE NDC.ID_REGISTRO = DND.NDC_ID_NOTA_DEBITO_CREDITO
    AND NDC.CTV_CO_TIPO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_TIPO_DOCUMENTO_NOTA_CREDITO_FISCAL')
    AND NDC.CTV_CO_ESTADO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_ESTADO_DOCUMENTO_EMITIDO')
         AND NDC.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
         AND (NDC.CTV_CO_MOTIVO_NOTA = SK00_BUSCAR.F_VCT('CO_MOTIVO_NOE_DEVOLUCION')
         OR NDC.CTV_CO_MOTIVO_NOTA = SK00_BUSCAR.F_VCT('CO_MOTIVO_AJUSTE_PRECIO_NCD'))
    AND NDC.ORG_ID_CLIENTE = NVL(NULL,NDC.ORG_ID_CLIENTE)
    AND FCL.ID_REGISTRO = NDC.FAC_ID_FACTURA
                             AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
    AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
    FROM S00_UBICACION_GEOGRAFICA
    START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
    CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
    GROUP BY NDC.CTV_CO_CLASE_ORGANIZACION
    ,NDC.CTV_DE_CLASE_ORGANIZACION
    ,NDC.CO_CLIENTE
    ,NDC.ORG_NB_CLIENTE
    ,FCL.PER_CO_IDENTIFICACION_VENDEDOR
    ,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    FCL.PER_NB_PRIMER_APELLIDO_VEND) DEV
    ,(SELECT RCD .CTV_CO_CLASE_ORGANIZACION CO_CLASE_CLIENTE
    ,RCD.CTV_DE_CLASE_ORGANIZACION DE_CLASE_CLIENTE
    ,RCD.CO_ORGANIZACION CO_CLIENTE
    ,RCD.ORG_NB_DISTRIBUIDOR NB_CLIENTE
    ,FCL.PER_CO_IDENTIFICACION_VENDEDOR CO_VENDEDOR
    ,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    FCL.PER_NB_PRIMER_APELLIDO_VEND NB_VENDEDOR
    ,SUM(RCD.MN_DESCUENTO) MN_DESCUENTO
    ,SUM(DECODE(SIGN(RCO.MN_COBRADO_ANTES - IVA.MN_IVA)
    ,-1
    ,RCD.MN_ABONO - ABS(RCO.MN_COBRADO_ANTES - IVA.MN_IVA)
    ,RCD.MN_ABONO)) MN_COBRADO
    FROM S06_RECIBO_COBRO_DOC_TOTAL_R RCD
    ,S04_FACTURA_CLIENTE_TOTAL_R FCL
    ,(SELECT ID_DOCUMENTO_REFERENCIA FAC_ID_FACTURA
    ,NVL(SUM(MN_DEBITO_CREDITO),0) MN_IVA
    FROM S04_DOCUMENTO_DEBITO_CREDITO_R
    WHERE TDC_CO_TIPO_DEBITO_CREDITO = SK00_BUSCAR.F_VCT('CO_TIPO_DEBITO_IVA')
    GROUP BY ID_DOCUMENTO_REFERENCIA) IVA
    ,(SELECT ID_REFERENCIA FAC_ID_FACTURA
    ,NVL(SUM(MN_ABONO),0) MN_COBRADO_ANTES
    FROM S06_RECIBO_COBRO_DOC_TOTAL_R
    WHERE FE_EMISION < to_date('01112009','ddmmyyyy')
    GROUP BY ID_REFERENCIA) RCO
         WHERE RCD.CTV_CO_ESTADO_DOCUMENTO = SK00_BUSCAR.F_VCT('CO_ESTADO_DOCUMENTO_EMITIDO')
         AND RCD.FE_EMISION BETWEEN to_date('01112009','ddmmyyyy') AND to_date('29112009','ddmmyyyy')
    AND RCD.ORG_ID_ORGANIZACION = NVL(NULL,RCD.ORG_ID_ORGANIZACION)
    AND FCL.CTV_CO_ESTADO_DOCUMENTO = 'EM'
                             AND FCL.ID_REGISTRO = RCD.ID_REFERENCIA
    AND FCL.UBG_ID_UBICACION_CLIENTE in (SELECT ID_REGISTRO
    FROM S00_UBICACION_GEOGRAFICA
    START WITH ID_REGISTRO = nvl(NULL, FCL.UBG_ID_UBICACION_CLIENTE)
    CONNECT BY PRIOR ID_REGISTRO = UBG_ID_UBICACION_PADRE)
    AND IVA.FAC_ID_FACTURA (+) = FCL.ID_REGISTRO
    AND RCO.FAC_ID_FACTURA (+) = FCL.ID_REGISTRO
    GROUP BY RCD.CTV_CO_CLASE_ORGANIZACION
    ,RCD.CTV_DE_CLASE_ORGANIZACION
    ,RCD.CO_ORGANIZACION
    ,RCD.ORG_NB_DISTRIBUIDOR
    ,FCL.PER_CO_IDENTIFICACION_VENDEDOR
    ,FCL.PER_NB_PRIMER_NOMBRE_VENDEDOR||' '||
    FCL.PER_NB_PRIMER_APELLIDO_VEND) COB
    WHERE VTA.CO_CLIENTE = DEV.CO_CLIENTE (+)
    AND VTA.CO_VENDEDOR = DEV.CO_VENDEDOR (+)
    AND VTA.CO_CLIENTE = COB.CO_CLIENTE (+)
    AND VTA.CO_VENDEDOR = COB.CO_VENDEDOR (+)
    ORDER BY VTA.NB_VENDEDOR
    ,VTA.CO_CLIENTE
    Is there a way i can influence the join method on this query ...?
    It's an XE DB.
    Regards, Luis ...!

    THIS IS THE PLAN:
    SQL> /
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=79006 Card=1 Bytes
    =253)
    1 0 SORT (ORDER BY) (Cost=79006 Card=1 Bytes=253)
    2 1 HASH JOIN (OUTER) (Cost=79005 Card=1 Bytes=253)
    3 2 HASH JOIN (OUTER) (Cost=78538 Card=1 Bytes=211)
    4 3 VIEW (Cost=78478 Card=1 Bytes=182)
    5 4 HASH (GROUP BY) (Cost=78478 Card=1 Bytes=232)
    6 5 FILTER
    7 6 HASH JOIN (OUTER) (Cost=78469 Card=1 Bytes=232
    8 7 TABLE ACCESS (BY INDEX ROWID) OF 'T04_FACTUR
    A_PRODUCTO' (TABLE) (Cost=2 Card=1 Bytes=46)
    9 8 NESTED LOOPS (Cost=25 Card=1 Bytes=213)
    10 9 VIEW OF 'V04_FACTURA_CLIENTE_TOTAL_R' (V
    IEW) (Cost=23 Card=1 Bytes=167)
    11 10 NESTED LOOPS (Cost=23 Card=1 Bytes=284
    12 11 NESTED LOOPS (OUTER) (Cost=23 Card=1
    Bytes=278)
    13 12 HASH JOIN (SEMI) (Cost=23 Card=1 B
    ytes=272)
    14 13 NESTED LOOPS (Cost=17 Card=1 Byt
    es=259)
    15 14 NESTED LOOPS (Cost=16 Card=1 B
    ytes=218)
    16 15 NESTED LOOPS (OUTER) (Cost=1
    6 Card=1 Bytes=212)
    17 16 NESTED LOOPS (Cost=15 Card
    =1 Bytes=179)
    18 17 NESTED LOOPS (Cost=15 Ca
    rd=1 Bytes=173)
    19 18 NESTED LOOPS (OUTER) (
    Cost=14 Card=1 Bytes=162)
    20 19 NESTED LOOPS (OUTER)
    (Cost=14 Card=1 Bytes=156)
    21 20 NESTED LOOPS (OUTE
    R) (Cost=14 Card=1 Bytes=150)
    22 21 NESTED LOOPS (OU
    TER) (Cost=14 Card=1 Bytes=144)
    23 22 NESTED LOOPS (
    Cost=14 Card=1 Bytes=105)
    24 23 SORT (UNIQUE
    ) (Cost=2 Card=1 Bytes=13)
    25 24 TABLE ACCE
    SS (FULL) OF 'T00_GRUPO_DATO_USUARIO_ACTIVO' (TABLE (TEMP))
    (Cost=2 Card=1 Bytes=13)
    26 23 TABLE ACCESS
    (BY INDEX ROWID) OF 'T04_FACTURA' (TABLE) (Cost=11 Card=1 B
    ytes=92)
    27 26 INDEX (RAN
    GE SCAN) OF 'I04_FAC_FE_EMISION' (INDEX) (Cost=10 Card=2)
    28 22 TABLE ACCESS (
    BY INDEX ROWID) OF 'T03_EMPRESA_SUCURSAL' (TABLE) (Cost=0 Ca
    rd=1 Bytes=39)
    29 28 INDEX (RANGE
    SCAN) OF 'I03_EMS_EMP' (INDEX) (Cost=0 Card=1)
    30 21 INDEX (UNIQUE SC
    AN) OF 'PK_PRY' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
    31 20 INDEX (UNIQUE SCAN
    ) OF 'PK_CAJ' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
    32 19 INDEX (UNIQUE SCAN)
    OF 'PK_PEC' (INDEX (UNIQUE)) (Cost=0 Card=1 Bytes=6)
    33 18 TABLE ACCESS (BY INDEX
    ROWID) OF 'T00_CONTENIDO_TABLA_VIRTUAL' (TABLE) (Cost=1 Car
    d=1 Bytes=11)
    34 33 INDEX (UNIQUE SCAN)
    OF 'PK_CTV' (INDEX (UNIQUE)) (Cost=0 Card=1)
    SORRY EXPLAIN OUTPUT TRUNCATED DUE TO SPACE RESTRICION .....
    Any help would be greatly appreciated.
    I believe there must be a way to influence on the tha costly HASH JOIN operation
    SQL> SPOOL OFF

  • Can u help me refine this query

    create table company
    (comp_id number primary key,
    comp_name varchar2(50) not null
    create table accident
    (acc_seq number primary key,
    acc_comp_id number not null,
    acc_series smallint not null,
    acc_id varchar2(10) not null,
    acc_type varchar2(50) not null)
    -- acc_series is an auto number to tell me total accident this company has so far
    insert into company(comp_id,comp_name)
    values(10001,'A Corp')
    insert into company(comp_id,comp_name)
    values(10002,'B Corp')
    insert into company(comp_id,comp_name)
    values(10003,'C Corp')
    insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
    values(9001,10001,1,'AC-09-0001','CAR')
    insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
    values(9002,10002,1,'AC-09-0002','MACHINARY')
    insert into accident(acc_seq,acc_comp_id,acc_series,acc_id,acc_type)
    values(9003,10001,2,'AC-09-0009','FIELD')
    -- problem for this query : I hardcoded number 1,2. In reality, I need a way to find the upper bound first then do the decode ( I think) and adjust the column heading accordingly, can u help ?
    select
    comp_name,
    max(decode(acc_series,1,acc_id)) acc1_id,
    max(decode(acc_series,1,acc_type)) acc1_type,
    max(decode(acc_series,2,acc_id)) acc2_id,
    max(decode(acc_series,2,acc_type)) acc2_type
    from company A,accident B
    where A.comp_id=B.acc_comp_id
    group by comp_name
    output
    COMP_NAME ACC1_ID ACC1_TYPE ACC2_ID ACC2_TYPE
    A Corp      AC-09-0001      CAR      AC-09-0009      FIELD
    B Corp      AC-09-0002      MACHINARY
    Thanks in advance.
    Munshar

    It looks like you are after a dynamic pivot.
    Check out this post by Frank that goes through an example on how to create a dynamic pivot: {message:id=3227388}

  • Help me in this query

    My Dear
    if I have table like emp table in scott plus new column month_sal
    And I write qery like this
    select ename,avg(sal) from emp
    where month_sal=2
    group by ename
    no Problem up to now
    I need Improve this query to be like this
    select ename,avg(sal) current_month,avg(sal) previous_month from emp
    where month_sal=2
    group by ename
    I need make another avgearge but for previuos parametre month
    thanks in advance

    user222 wrote:
    PLZ I need your helpIt would help if you provided some suitable example data and expected output for us so it was clear what you wanted, as described in the FAQ: {message:id=9360002}
    Perhaps this helps...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 1 as item_code, 20 as item_price, 1 as mnth, 2011 as yr from dual union all
      2             select 2, 30, 1, 2011 from dual union all
      3             select 3, 15, 1, 2011 from dual union all
      4             select 4, 7, 2, 2011 from dual union all
      5             select 5, 8, 2, 2011 from dual union all
      6             select 6, 9, 2, 2011 from dual union all
      7             select 7, 10, 2, 2011 from dual union all
      8             select 8, 14, 3, 2011 from dual union all
      9             select 9, 21, 3, 2011 from dual union all
    10             select 10, 7, 4, 2011 from dual union all
    11             select 11, 10, 4, 2011 from dual union all
    12             select 12, 13, 4, 2011 from dual)
    13  --
    14  -- end of test data
    15  --
    16  select mnth, yr, mnth_avg_price
    17        ,lag(mnth_avg_price) over (order by yr, mnth) as prev_mnth_avg_price
    18  from (
    19        select mnth, yr, avg(item_price) as mnth_avg_price
    20        from t
    21        group by mnth, yr
    22       )
    23* order by yr, mnth
    SQL> /
          MNTH         YR MNTH_AVG_PRICE PREV_MNTH_AVG_PRICE
             1       2011     21.6666667
             2       2011            8.5          21.6666667
             3       2011           17.5                 8.5
             4       2011             10                17.5
    SQL>

  • Help need in this query

    Hi All,
    I create following query which return my required results. but when i insert a new entry in the table it returns a new group of the same month and not add it in the above group where i doing mistake any idea ????
    My required results
    SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
      2   t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
      3  from pos t
      4  group by t.pos_date,t.asset;
    MONTH      DATE_REC    AMOUNT ASSET      AVG_ORA_COL Normal Average
    November          3       750 Loans              250            250
    December          2       900 Loans              450            450
    SQL> select * from pos;
    POS_DATE  ASSET         AMOUNT
    01-NOV-07 Loans            100
    01-NOV-07 Loans            250
    01-NOV-07 Loans            400
    02-NOV-07 Loans            100
    02-NOV-07 Loans            250
    02-NOV-07 Loans            400
    03-NOV-07 Loans            100
    03-NOV-07 Loans            250
    03-NOV-07 Loans            400
    09-DEC-07 Loans            500
    09-DEC-07 Loans            400
    11 rows selected.
    After insertion records in table it looks like following:
    SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
      2   t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
      3  from pos t
      4  group by t.pos_date,t.asset;
    MONTH      DATE_REC    AMOUNT ASSET      AVG_ORA_COL Normal Average
    November          3       750 Loans              250            250
    December          2       900 Loans              450            450
    November          1       300 Loans              300            300
    December          1       300 Loans              300            300
    SQL> select * from pos;
    POS_DATE  ASSET         AMOUNT
    01-NOV-07 Loans            100
    01-NOV-07 Loans            250
    01-NOV-07 Loans            400
    02-NOV-07 Loans            100
    02-NOV-07 Loans            250
    02-NOV-07 Loans            400
    03-NOV-07 Loans            100
    03-NOV-07 Loans            250
    03-NOV-07 Loans            400
    09-DEC-07 Loans            500
    09-DEC-07 Loans            400
    10-DEC-07 Loans            300
    27-NOV-07 Loans            300
    13 rows selected.
    My requirment is following
    SQL> SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
      2   t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
      3  from pos t
      4  group by t.pos_date,t.asset;
    MONTH      DATE_REC    AMOUNT ASSET     
    November          4       637 Loans             
    December          2      600 Loans              I want to divide no. of occurance of dates.
    which is 4 in Nov and 2 in dec.
    Message was edited by:
    53637

    hi,
    try this query
    Instead of grouping by t.pos_date group by TO_CHAR(T.POS_DATE, 'Month')
    SELECT DISTINCT TO_CHAR(T.POS_DATE, 'Month') Month,count(*) Date_rec,sum(t.amount) amount,
    t.Asset, avg(t.amount) avg_ora_col,Sum(t.amount)/ count(*) "Normal Average"
    from pos t
    group by TO_CHAR(T.POS_DATE, 'Month'),t.asset
    hope this will work
    Regards,
    Sridhar

  • Hi Everyone...Please help me with this query...!

    Please Help me with this doubt as I am unable to understand the logic...behind this code. It's a begineer level code but I need to understand the logic so that I am able to grasp knowledge. Thank you all for being supportive. Please help me.
    //Assume class Demo is inherited from class SuperDemo...in other words class Demo extends SuperDemo
    //Volume is a method declared in SuperDemo which returns an integer value
    //weight is an integer vairable declared in the subclass which is Demo
    class Example
         public static void main(String qw[])
              Demo ob1=new Demo(3,5,7,9);
    //Calling Constructor of Demo which takes in 4 int parameters
              SuperDemo ob2=new SuperDemo();
              int vol;
              vol=ob1.volume();
              System.out.println("Volume of ob1 is " + vol);
              System.out.println("Weight of ob1 is " + ob1.weight);
              System.out.println();
              ob2=ob1;
    }Can someone please make me understand --- how is this possible and why !
    If the above statement is valid then why not this one "System.out.println(ob2.weight);"
    Thanks Thanks Thanks!

    u see the line wherein I am referencing the objectof
    a subclass to the superclass...right? then why we
    can't do System.out.println(ob2.weight)?You need to distinguish two things:
    - the type of the object, which determines with the
    object can do
    - the type of the reference to the object, which
    determines what you see that you can do
    Both don't necessarily have to match. When you use a
    SuperDemo reference (obj2) to access a Demo instance
    (obj1), for all you know, the instance behind obj2 is
    of type SuperDemo. That it's in reality of type Demo
    is unknown to you. And usually, you don't care -
    that's what polymorphism is about.
    So you have a reference obj2 of type SuperDemo.
    SuperDemo objects don't have weight, so you don't see
    it - even though it is there.So from ur explanation wat I understand is - Even though u reference a subclass object to a superclass, u will only be able to access the members which are declared in the superclass thru the same...right
    ?

Maybe you are looking for