Help in rewrite the Query

Hello
I have one query taking time to fetch the records. Table contains just 40,000 thousands records but lots of case statement in the query, I just remove lots of case statement there are lot more...
Can you please help me out to rewrite the query to fetch the records faster. Also Right now there are no indexes on the table....
SELECT O.cn,
       O.BEN_LAST_NAME,
       O.BEN_FIRST_NAME,
       O.BEN_MI,
       O.SSN,
       O.DOB,
       O.SEX,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 00 AND 34 THEN
           1
          ELSE
           0
       END AS AGE_GROUP0_34_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 35 AND 44 THEN
           1
          ELSE
           0
       END AS AGE_GROUP35_44_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 45 AND 54 THEN
           1
          ELSE
           0
       END AS AGE_GROUP45_54_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 55 AND 59 THEN
           1
          ELSE
           0
       END AS AGE_GROUP55_59_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 60 AND 64 THEN
           1
          ELSE
           0
       END AS AGE_GROUP60_64_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 65 AND 69 THEN
           1
          ELSE
           0
       END AS AGE_GROUP65_69_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 70 AND 74 THEN
           1
          ELSE
           0
       END AS AGE_GROUP70_74_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 75 AND 79 THEN
           1
          ELSE
           0
       END AS AGE_GROUP75_79_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 80 AND 84 THEN
           1
          ELSE
           0
       END AS AGE_GROUP80_84_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 85 AND 89 THEN
           1
          ELSE
           0
       END AS AGE_GROUP85_89_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 90 AND 94 THEN
           1
          ELSE
           0
       END AS AGE_GROUP90_94_F,
       CASE
          WHEN O.SEX = 'F' AND O.AGE BETWEEN 95 AND 00 THEN
           1
          ELSE
           0
       END AS AGE_GROUP95_GT_F,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 00 AND 34 THEN
           1
          ELSE
           0
       END AS AGE_GROUP0_34_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 35 AND 44 THEN
           1
          ELSE
           0
       END AS AGE_GROUP35_44_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 45 AND 54 THEN
           1
          ELSE
           0
       END AS AGE_GROUP45_54_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 45 AND 59 THEN
           1
          ELSE
           0
       END AS AGE_GROUP55_59_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 60 AND 64 THEN
           1
          ELSE
           0
       END AS AGE_GROUP60_64_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 65 AND 69 THEN
           1
          ELSE
           0
       END AS AGE_GROUP65_69_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 70 AND 74 THEN
           1
          ELSE
           0
       END AS AGE_GROUP70_74_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 75 AND 79 THEN
           1
          ELSE
           0
       END AS AGE_GROUP75_79_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 80 AND 84 THEN
           1
          ELSE
           0
       END AS AGE_GROUP80_84_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 85 AND 89 THEN
           1
          ELSE
           0
       END AS AGE_GROUP85_89_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 90 AND 94 THEN
           1
          ELSE
           0
       END AS AGE_GROUP90_94_M,
       CASE
          WHEN O.SEX = 'M' AND O.AGE BETWEEN 95 AND 00 THEN
           1
          ELSE
           0
       END AS AGE_GROUP95_GT_M,
       O.YEAR,
      CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                        ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                        AND m2.YEAR = hm.YEAR
                        AND o.cn = m2.cn
                        AND o.YEAR = hm.YEAR
                        AND m1.hcc_model_category1 = 1
                        AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS DISEASE_COEF_HCC1,
      CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                        ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                        AND m2.YEAR = hm.YEAR
                        AND o.cn = m2.cn
                        AND o.YEAR = hm.YEAR
                        AND m1.hcc_model_category1 = 2
                        AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS DISEASE_COEF_HCC2,
       CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                        ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                        AND m2.YEAR = hm.YEAR
                        AND o.cn = m2.cn
                        AND o.YEAR = hm.YEAR
                        AND m1.hcc_model_category1 = 5
                         AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS       DISEASE_COEF_HCC5,
        CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                        ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                        AND m2.YEAR = hm.YEAR
                        AND o.cn = m2.cn
                        AND o.YEAR = hm.YEAR
                        AND m1.hcc_model_category1 = 7
                        AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS      DISEASE_COEF_HCC7,
       CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                        ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                        AND m2.YEAR = hm.YEAR
                        AND o.cn = m2.cn
                        AND o.YEAR = hm.YEAR
                        AND m1.hcc_model_category1 = 8
                        AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS       DISEASE_COEF_HCC8                   
  FROM (SELECT T.cn,
               T.BEN_LAST_NAME,
               T.BEN_FIRST_NAME,
               T.BEN_MI,
               T.SSN,
               TO_DATE(T.DOB, 'YYYYMMDD') AS DOB,
               T.SEX,
               TRUNC(MONTHS_BETWEEN(TO_DATE('01/01/' || T.YEAR, 'MM/DD/YYYY'),
                                    TO_DATE(T.DOB, 'YYYYMMDD')) / 12) AS AGE,
               T.YEAR
          FROM mor111 T ) O Thanks in advance!
Kind regards,
Nik

Ok, so I am going to be a little bit kinder then your first reply, but not much.
From what can tell you are doing medical management and are trying to select by AGE/GENDER CELLS and this is common when trying to deal with RBRVS.
This is by far some of the worst sql I have ever seen, sorry but it just is.
So please report this either as a new post or as a reply and:
1. At least post the table definitions and if you can some sample data.
2. Get rid of almost all the case selectors.
3. Describe the output you need.
As it is this is unreadable.
After that we can talk more.
Edited by: FlyingGuy on Oct 11, 2011 5:13 PM

Similar Messages

  • Help to rewrite the query --performance issue

    Hi ,
    Please help to rewrite the query since it's performance is not good.Especially second inline query(CASE statements are therein select caluse ..)is taking more cost.
    Database Oracle Database 10g Enterprise Edition Release 10.2.0.2.0 - 64bi
    SELECT *
    FROM
      (SELECT q.*,
        COUNT(*) OVER() AS record_count,
        ROWNUM          AS row_num
      FROM
        (SELECT ExName.examiner_code,
          examiner_name,
          :v_year,
          :v_month,
          count_fb,
          NVL(count_entered_fb, 0) count_entered_fb,
          NVL(count_sent_fb, 0) count_sent_fb,
          NVL(count_edited_fb, 0) count_edited_fb,
          NVL(count_complete_fb, 0) count_complete_fb,
          NVL(count_withibcardiff_fb, 0) count_withibcardiff_fb
        FROM
          (SELECT examiner_code,
            COUNT(*) AS count_fb
          FROM
            (SELECT
                        examiner_code,
              paper_code,
              assessment_school
            FROM
              ( SELECT DISTINCT ce.examiner_code,
                ce.paper_code,
                ce.assessment_school
              FROM
                (SELECT
                  DISTINCT assessment_school,
                  paper_code,
                  examiner_code
                FROM candidate_examiner_allocation cea
                WHERE cea.element = 'Moderation of IA'
                AND cea.year      = :v_year
                AND cea.month     = :v_month
                ) ce,
                subject_group sg,
                subject_component sc
              WHERE (:v_padded_examiner_code IS NULL
              OR ce.examiner_code            = :v_padded_examiner_code)
              AND (:v_subject_group          IS NULL
              OR sg.group_number             = :v_subject_group)
              AND sg.year                    = :v_year
              AND sg.month                   = :v_month
              AND sc.year                    = :v_year
              AND sc.month                   = :v_month
              AND sc.paper_code              = ce.paper_code
              AND sc.subject                 = sg.subject
              AND sc.lvl                     = sg.lvl
              AND (:v_subject                IS NULL
              OR sc.subject                  = :v_subject)
              AND (:v_lvl                    IS NULL
              OR sc.lvl                      = :v_lvl)
              ) ea
          GROUP BY examiner_code
          ) ExName,
          (SELECT examiner_code,
            COUNT(
            CASE
              WHEN UPPER(wfi.status) = 'ENTERED'
              THEN 1
              ELSE NULL
            END) AS count_entered_fb,
            COUNT(
            CASE
              WHEN UPPER(wfi.status) = 'SENT'
              THEN 1
              ELSE NULL
            END) AS count_sent_fb,
            COUNT(
            CASE
              WHEN UPPER(wfi.status) = 'EDITED'
              THEN 1
              ELSE NULL
            END) AS count_edited_fb,
            COUNT(
            CASE
              WHEN UPPER(wfi.status) = 'COMPLETE'
              THEN 1
              ELSE NULL
            END) AS count_complete_fb,
            COUNT(
            CASE
              WHEN UPPER(wfi.status) = 'WITH IBCARDIFF'
              THEN 1
              ELSE NULL
            END) AS count_withibcardiff_fb
          FROM ia_instances ia1,
            workflow_instance wfi
          WHERE wfi.instance_id = ia1.workflow_instance_id
          AND ia1.year          = :v_year
          AND ia1.month         = :v_month
          GROUP BY ia1.year,
            ia1.month,
            examiner_code
          ) iaF,
          (SELECT person_code,
            title
            || ' '
            || firstname
            || ' '
            || lastname AS examiner_name
          FROM person
          WHERE :v_examiner_name IS NULL
          OR UPPER(title
            || ' '
            || firstname
            || ' '
            || lastname) LIKE :v_search_examiner_name
          ) P
        WHERE ExName.examiner_code = iaF.examiner_code (+)
        AND ExName.examiner_code   = p.person_code
        ORDER BY ExName.examiner_code
        ) q
      ) rc
    WHERE row_num >= :v_start_row
    AND row_num   <= (:v_start_row+(:v_max_row-1));explain plan
    line 1: SQLPLUS Command Skipped: set linesize 130
    line 2: SQLPLUS Command Skipped: set pagesize 0
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    Plan hash value: 1581970599                                                                                                                                                                                                                                                                                 
    | Id  | Operation                                 | Name                           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |                                                                                                                                                                        
    |   0 | SELECT STATEMENT                          |                                |     1 |   276 |       |  2187   (6)| 00:00:34 |                                                                                                                                                                        
    |*  1 |  FILTER                                   |                                |       |       |       |            |          |                                                                                                                                                                        
    |*  2 |   VIEW                                    |                                |     1 |   276 |       |  2187   (6)| 00:00:34 |                                                                                                                                                                        
    |   3 |    WINDOW BUFFER                          |                                |     1 |   250 |       |  2187   (6)| 00:00:34 |                                                                                                                                                                        
    |   4 |     COUNT                                 |                                |       |       |       |            |          |                                                                                                                                                                        
    |   5 |      VIEW                                 |                                |     1 |   250 |       |  2187   (6)| 00:00:34 |                                                                                                                                                                        
    |   6 |       SORT ORDER BY                       |                                |     1 |   119 |       |  2187   (6)| 00:00:34 |                                                                                                                                                                        
    |   7 |        NESTED LOOPS                       |                                |     1 |   119 |       |  2186   (6)| 00:00:34 |                                                                                                                                                                        
    |*  8 |         HASH JOIN OUTER                   |                                |     1 |    92 |       |  2185   (6)| 00:00:34 |                                                                                                                                                                        
    |   9 |          VIEW                             |                                |     1 |    20 |       |    51   (4)| 00:00:01 |                                                                                                                                                                        
    |  10 |           SORT GROUP BY                   |                                |     1 |     7 |       |    51   (4)| 00:00:01 |                                                                                                                                                                        
    |  11 |            VIEW                           |                                |     1 |     7 |       |    51   (4)| 00:00:01 |                                                                                                                                                                        
    |  12 |             SORT UNIQUE                   |                                |     1 |   127 |       |    51   (4)| 00:00:01 |                                                                                                                                                                        
    |  13 |              NESTED LOOPS                 |                                |     1 |   127 |       |    50   (2)| 00:00:01 |                                                                                                                                                                        
    |* 14 |               HASH JOIN                   |                                |     1 |    68 |       |    44   (3)| 00:00:01 |                                                                                                                                                                        
    |* 15 |                TABLE ACCESS BY INDEX ROWID| SUBJECT_COMPONENT              |    13 |   520 |       |    40   (0)| 00:00:01 |                                                                                                                                                                        
    |* 16 |                 INDEX RANGE SCAN          | SUBJECT_COMPONENT_ASSESS_TYPE  |  1059 |       |       |     9   (0)| 00:00:01 |                                                                                                                                                                        
    |* 17 |                INDEX RANGE SCAN           | SUBJECT_GROUP_PK               |    41 |  1148 |       |     3   (0)| 00:00:01 |                                                                                                                                                                        
    |* 18 |               INDEX RANGE SCAN            | CEA_AUTOMATIC_ALLOCATION_STATS |     5 |   295 |       |     6   (0)| 00:00:01 |                                                                                                                                                                        
    |  19 |          VIEW                             |                                |   679 | 48888 |       |  2133   (6)| 00:00:33 |                                                                                                                                                                        
    |  20 |           SORT GROUP BY                   |                                |   679 | 25123 |       |  2133   (6)| 00:00:33 |                                                                                                                                                                        
    |* 21 |            HASH JOIN                      |                                | 52408 |  1893K|  1744K|  2126   (6)| 00:00:33 |                                                                                                                                                                        
    |  22 |             TABLE ACCESS BY INDEX ROWID   | IA_INSTANCES                   | 52408 |  1125K|       |   688   (1)| 00:00:11 |                                                                                                                                                                        
    |* 23 |              INDEX RANGE SCAN             | IND_IA_INSTANCES               | 49077 |       |       |   137   (2)| 00:00:03 |                                                                                                                                                                        
    |  24 |             TABLE ACCESS FULL             | WORKFLOW_INSTANCE              |  1075K|    15M|       |   960   (7)| 00:00:15 |                                                                                                                                                                        
    |* 25 |         TABLE ACCESS BY INDEX ROWID       | PERSON                         |     1 |    27 |       |     1   (0)| 00:00:01 |                                                                                                                                                                        
    |* 26 |          INDEX UNIQUE SCAN                | PERSON_PK                      |     1 |       |       |     0   (0)| 00:00:01 |                                                                                                                                                                        
    Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       1 - filter(TO_NUMBER(:V_START_ROW)<=TO_NUMBER(:V_START_ROW)+(TO_NUMBER(:V_MAX_ROW)-1))                                                                                                                                                                                                                   
       2 - filter("ROW_NUM">=TO_NUMBER(:V_START_ROW) AND "ROW_NUM"<=TO_NUMBER(:V_START_ROW)+(TO_NUMBER(:V_MAX_ROW)-1))                                                                                                                                                                                          
       8 - access("EXNAME"."EXAMINER_CODE"="IAF"."EXAMINER_CODE"(+))                                                                                                                                                                                                                                            
      14 - access("SC"."SUBJECT"="SG"."SUBJECT" AND "SC"."LVL"="SG"."LVL")                                                                                                                                                                                                                                      
      15 - filter((:V_SUBJECT IS NULL OR "SC"."SUBJECT"=:V_SUBJECT) AND ("SC"."LVL"=:V_LVL OR :V_LVL IS NULL))                                                                                                                                                                                                  
      16 - access("SC"."YEAR"=TO_NUMBER(:V_YEAR) AND "SC"."MONTH"=:V_MONTH)                                                                                                                                                                                                                                     
      17 - access("SG"."YEAR"=TO_NUMBER(:V_YEAR) AND "SG"."MONTH"=:V_MONTH)                                                                                                                                                                                                                                     
           filter(:V_SUBJECT_GROUP IS NULL OR "SG"."GROUP_NUMBER"=TO_NUMBER(:V_SUBJECT_GROUP))                                                                                                                                                                                                                  
      18 - access("CEA"."YEAR"=TO_NUMBER(:V_YEAR) AND "CEA"."MONTH"=:V_MONTH AND "SC"."PAPER_CODE"="PAPER_CODE" AND                                                                                                                                                                                             
                  "CEA"."ELEMENT"='Moderation of IA')                                                                                                                                                                                                                                                           
           filter("CEA"."ELEMENT"='Moderation of IA' AND (:V_PADDED_EXAMINER_CODE IS NULL OR                                                                                                                                                                                                                    
                  "EXAMINER_CODE"=:V_PADDED_EXAMINER_CODE))                                                                                                                                                                                                                                                     
      21 - access("WFI"."INSTANCE_ID"="IA1"."WORKFLOW_INSTANCE_ID")                                                                                                                                                                                                                                             
      23 - access("IA1"."YEAR"=TO_NUMBER(:V_YEAR) AND "IA1"."MONTH"=:V_MONTH)                                                                                                                                                                                                                                   
      25 - filter(:V_EXAMINER_NAME IS NULL OR UPPER("TITLE"||' '||"FIRSTNAME"||' '||"LASTNAME") LIKE :V_SEARCH_EXAMINER_NAME)                                                                                                                                                                                   
      26 - access("EXNAME"."EXAMINER_CODE"="PERSON_CODE")                                                                                                                                                                                                                                                       
    53 rows selected

    Hi,
    please find the below rigjt explan paln.
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    SQL_ID  2ct41vyyzqyh7, child number 0                                                                                                                                                                                                                                                                       
    SELECT *  FROM    (SELECT q.*,      COUNT(*) OVER() AS record_count,      ROWNUM          AS row_num    FROM      (SELECT                                                                                                                                                                                   
    ExName.examiner_code,        examiner_name,        :v_year,        :v_month,        count_fb,        NVL(count_entered_fb,                                                                                                                                                                                  
    0) count_entered_fb,        NVL(count_sent_fb, 0) count_sent_fb,        NVL(count_edited_fb, 0) count_edited_fb,                                                                                                                                                                                            
    NVL(count_complete_fb, 0) count_complete_fb,        NVL(count_withibcardiff_fb, 0) count_withibcardiff_fb      FROM                                                                                                                                                                                         
    (SELECT examiner_code,          COUNT(*) AS count_fb        FROM          (SELECT                                                                                                                                                                                                 
           examiner_code,            paper_code,            assessment_school          FROM            ( SELECT DISTINCT                                                                                                                                                                                        
    ce.examiner_code,              ce.paper_code,              ce.assessment_school            FROM              (SELECT                                                                                                                                                                                        
                            DISTINCT assessment_school,                                                                                                                                                                                                          
    paper_code,                examiner                                                                                                                                                                                                                                                                         
    Plan hash value: 651311258                                                                                                                                                                                                                                                                                  
    | Id  | Operation                                | Name                           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |                                                                                                                                                                         
    |   0 | SELECT STATEMENT                         |                                |       |       |       |  2785 (100)|          |                                                                                                                                                                         
    |*  1 |  FILTER                                  |                                |       |       |       |            |          |                                                                                                                                                                         
    |*  2 |   VIEW                                   |                                |     4 |  1104 |       |  2785   (7)| 00:00:43 |                                                                                                                                                                         
    |   3 |    WINDOW BUFFER                         |                                |     4 |  1000 |       |  2785   (7)| 00:00:43 |                                                                                                                                                                         
    |   4 |     COUNT                                |                                |       |       |       |            |          |                                                                                                                                                                         
    |   5 |      VIEW                                |                                |     4 |  1000 |       |  2785   (7)| 00:00:43 |                                                                                                                                                                         
    |   6 |       NESTED LOOPS                       |                                |     4 |   476 |       |  2785   (7)| 00:00:43 |                                                                                                                                                                         
    |   7 |        MERGE JOIN OUTER                  |                                |     4 |   368 |       |  2781   (7)| 00:00:43 |                                                                                                                                                                         
    |   8 |         VIEW                             |                                |     4 |    80 |       |    72   (3)| 00:00:02 |                                                                                                                                                                         
    |   9 |          SORT GROUP BY                   |                                |     4 |    28 |       |    72   (3)| 00:00:02 |                                                                                                                                                                         
    |  10 |           VIEW                           |                                |     4 |    28 |       |    72   (3)| 00:00:02 |                                                                                                                                                                         
    |  11 |            SORT UNIQUE                   |                                |     4 |   508 |       |    72   (3)| 00:00:02 |                                                                                                                                                                         
    |  12 |             NESTED LOOPS                 |                                |     4 |   508 |       |    71   (2)| 00:00:02 |                                                                                                                                                                         
    |* 13 |              HASH JOIN                   |                                |     1 |    68 |       |    44   (3)| 00:00:01 |                                                                                                                                                                         
    |* 14 |               TABLE ACCESS BY INDEX ROWID| SUBJECT_COMPONENT              |    13 |   520 |       |    40   (0)| 00:00:01 |                                                                                                                                                                         
    |* 15 |                INDEX RANGE SCAN          | SUBJECT_COMPONENT_ASSESS_TYPE  |  1059 |       |       |     9   (0)| 00:00:01 |                                                                                                                                                                         
    |* 16 |               INDEX RANGE SCAN           | SUBJECT_GROUP_PK               |    41 |  1148 |       |     3   (0)| 00:00:01 |                                                                                                                                                                         
    |* 17 |              INDEX RANGE SCAN            | CEA_AUTOMATIC_ALLOCATION_STATS |    30 |  1770 |       |    27   (0)| 00:00:01 |                                                                                                                                                                         
    |* 18 |         SORT JOIN                        |                                |   576 | 41472 |       |  2709   (7)| 00:00:42 |                                                                                                                                                                         
    |  19 |          VIEW                            |                                |   576 | 41472 |       |  2708   (7)| 00:00:42 |                                                                                                                                                                         
    |  20 |           SORT GROUP BY                  |                                |   576 | 21312 |       |  2708   (7)| 00:00:42 |                                                                                                                                                                         
    |* 21 |            HASH JOIN                     |                                | 52408 |  1893K|  1744K|  2701   (7)| 00:00:41 |                                                                                                                                                                         
    |* 22 |             TABLE ACCESS FULL            | IA_INSTANCES                   | 52408 |  1125K|       |  1263   (6)| 00:00:20 |                                                                                                                                                                         
    |  23 |             TABLE ACCESS FULL            | WORKFLOW_INSTANCE              |  1075K|    15M|       |   960   (7)| 00:00:15 |                                                                                                                                                                         
    |* 24 |        TABLE ACCESS BY INDEX ROWID       | PERSON                         |     1 |    27 |       |     1   (0)| 00:00:01 |                                                                                                                                                                         
    |* 25 |         INDEX UNIQUE SCAN                | PERSON_PK                      |     1 |       |       |     0   (0)|          |                                                                                                                                                                         
    Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       1 - filter(TO_NUMBER(:V_START_ROW)<=TO_NUMBER(:V_START_ROW)+(TO_NUMBER(:V_MAX_ROW)-1))                                                                                                                                                                                                                   
       2 - filter(("ROW_NUM">=TO_NUMBER(:V_START_ROW) AND "ROW_NUM"<=TO_NUMBER(:V_START_ROW)+(TO_NUMBER(:V_MAX_ROW)-1)))                                                                                                                                                                                        
      13 - access("SC"."SUBJECT"="SG"."SUBJECT" AND "SC"."LVL"="SG"."LVL")                                                                                                                                                                                                                                      
      14 - filter(((:V_SUBJECT IS NULL OR "SC"."SUBJECT"=:V_SUBJECT) AND ("SC"."LVL"=:V_LVL OR :V_LVL IS NULL)))                                                                                                                                                                                                
      15 - access("SC"."YEAR"=TO_NUMBER(:V_YEAR) AND "SC"."MONTH"=:V_MONTH)                                                                                                                                                                                                                                     
      16 - access("SG"."YEAR"=TO_NUMBER(:V_YEAR) AND "SG"."MONTH"=:V_MONTH)                                                                                                                                                                                                                                     
           filter((:V_SUBJECT_GROUP IS NULL OR "SG"."GROUP_NUMBER"=TO_NUMBER(:V_SUBJECT_GROUP)))                                                                                                                                                                                                                
      17 - access("CEA"."YEAR"=TO_NUMBER(:V_YEAR) AND "CEA"."MONTH"=:V_MONTH AND "SC"."PAPER_CODE"="PAPER_CODE" AND                                                                                                                                                                                             
                  "CEA"."ELEMENT"='Moderation of IA')                                                                                                                                                                                                                                                           
           filter(("CEA"."ELEMENT"='Moderation of IA' AND (:V_PADDED_EXAMINER_CODE IS NULL OR                                                                                                                                                                                                                   
                  "EXAMINER_CODE"=:V_PADDED_EXAMINER_CODE)))                                                                                                                                                                                                                                                    
      18 - access("EXNAME"."EXAMINER_CODE"="IAF"."EXAMINER_CODE")                                                                                                                                                                                                                                               
           filter("EXNAME"."EXAMINER_CODE"="IAF"."EXAMINER_CODE")                                                                                                                                                                                                                                               
      21 - access("WFI"."INSTANCE_ID"="IA1"."WORKFLOW_INSTANCE_ID")                                                                                                                                                                                                                                             
      22 - filter(("IA1"."MONTH"=:V_MONTH AND "IA1"."YEAR"=TO_NUMBER(:V_YEAR)))                                                                                                                                                                                                                                 
      24 - filter((:V_EXAMINER_NAME IS NULL OR UPPER("TITLE"||' '||"FIRSTNAME"||' '||"LASTNAME") LIKE :V_SEARCH_EXAMINER_NAME))                                                                                                                                                                                 
      25 - access("EXNAME"."EXAMINER_CODE"="PERSON_CODE")                                                                                                                                                                                                                                                       
    66 rows selected

  • Help Required(Rewriting the query to reduce steps)

    With and Without Group ID,I am populating a value into a column,Can anyone please help to write the same query in an other way.This is a sample column.Likewise,there are 5 more columns to be populated.So that I have to write 2 left outer joins for a single column with a little difference.
    SELECT
    CASE
         WHEN T6.ACTUAL_FUNCTION IS NOT NULL
         THEN T6.ACTUAL_FUNCTION
         WHEN T10.ACTUAL_FUNCTION IS NOT NULL
         THEN T10.ACTUAL_FUCNTION
              ELSE T5.ACTUAL_FUCNTION
    END AF_NOM_PRE_GTEES
    FROM
    ABC_WT17 T1
         INNER JOIN
         ABC_CUSTOMER_WT01 T3
         ON T1.ORIGINAL_SDS_PARTY_IDR=T3.ORIGINAL_SDS_PARTY_IDR
         AND T1.IDR_TYPE_CODE=T3.IDR_TYPE_CODE
         LEFT OUTER JOIN /* This is the condition with group ID*/
         RESIDUAL_CONTROL T6
         ON
         T1.NOM_PRE_GTEES = T6.VALUE_MAX
         OR
         T1.NOM_PRE_GTEES > T6.VALUE_GREATER_THAN
         AND
         T1.NOM_PRE_GTEES < T6.VALUE_MAX
         AND
    _     T1.GROUP_ID = T6.GROUP_ID_
         AND
         T6.FALLBACK_IND = ‘N’
    LEFT OUTER JOIN /* this is the condition without Group ID*/
         RESIDUAL_CONTROL T10
         ON
         T1.NOM_PRE_GTEES = T10.VALUE_MAX
         OR
         T1.NOM_PRE_GTEES > T10.VALUE_GREATER_THAN
         AND
         T1.NOM_PRE_GTEES < T10.VALUE_MAX
         AND
         T10.FALLBACK_IND = ‘N’
         CROSS JOIN
         RESIDUAL_CONTROL T5
         ON T5.FALLBACK_IND = ‘Y’
    Thanks in advance.

    KVB wrote:
    With and Without Group ID,I am populating a value into a column,Can anyone please help to write the same query in an other way.This is a sample column.Likewise,there are 5 more columns to be populated.So that I have to write 2 left outer joins for a single column with a little difference.
    SELECT
    CASE
         WHEN T6.ACTUAL_FUNCTION IS NOT NULL
         THEN T6.ACTUAL_FUNCTION
         WHEN T10.ACTUAL_FUNCTION IS NOT NULL
         THEN T10.ACTUAL_FUCNTION
              ELSE T5.ACTUAL_FUCNTION
    END AF_NOM_PRE_GTEES
    FROM
    ABC_WT17 T1
         INNER JOIN
         ABC_CUSTOMER_WT01 T3
         ON T1.ORIGINAL_SDS_PARTY_IDR=T3.ORIGINAL_SDS_PARTY_IDR
         AND T1.IDR_TYPE_CODE=T3.IDR_TYPE_CODE
         LEFT OUTER JOIN /* This is the condition with group ID*/
         RESIDUAL_CONTROL T6
         ON
         T1.NOM_PRE_GTEES = T6.VALUE_MAX
         OR
         T1.NOM_PRE_GTEES > T6.VALUE_GREATER_THAN
         AND
         T1.NOM_PRE_GTEES < T6.VALUE_MAX
         AND
    _     T1.GROUP_ID = T6.GROUP_ID_
         AND
         T6.FALLBACK_IND = ‘N’
    LEFT OUTER JOIN /* this is the condition without Group ID*/
         RESIDUAL_CONTROL T10
         ON
         T1.NOM_PRE_GTEES = T10.VALUE_MAX
         OR
         T1.NOM_PRE_GTEES > T10.VALUE_GREATER_THAN
         AND
         T1.NOM_PRE_GTEES < T10.VALUE_MAX
         AND
         T10.FALLBACK_IND = ‘N’
         CROSS JOIN
         RESIDUAL_CONTROL T5
         ON T5.FALLBACK_IND = ‘Y’
    Thanks in advance.Thread: HOW TO: Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting

  • I need a help on Join please or anybody help to rewrite the query

    select
    x.QUEST_DESC,y.QUES_RESPONSE, y.user_id from
    (select c.QUES_CODE, c.QUEST_DESC, null user_id from CLINICAL_HISTORY_QUESTIONS c where c.CLINICAL_TYPE_CODE=2) x,
    (select a.QUEST_CODE, a.QUEST_RESPONSE, a.user_id from PATIENT_CLINICAL_HISTORIES a where a.CLINICAL_TYPE_CODE=2 and a.user_ID=88) y
    where x.QUEST_CODE =y.QUEST_CODE(+)
    Is there any way I can display same user_ID 88 on the null USER_ID (Joined one)
    my result is
    QUEST_DESC     QUEST_RESPONSE     USER_ID
    Fibrostenotic               U     88
    Inflammatory               U     88
    Int Penetrating/Perforating          U     88
    Perianal Perforating Disease          U     88
    Uc Like                    U     88
    Iv Therapy          
    Fistula          
    Bleeding          
    Osteopenia          
    Sibo          
    Urgency          
    Extraintestinal Sx          
    Steroid Dependent          
    Immunosuppressive Tx          
    Fever/Chills          
    Obstructive Sx          
    Stool Consistency          
    Adb Pain          
    Other          
    Growth          
    Osteoporosis          
    Stool Frequency          
    Flare Of Disease
    Edited by: Paul Vellackel on Jul 2, 2010 3:20 PM
    Edited by: Paul Vellackel on Jul 2, 2010 3:55 PM

    sigh
    What we were asking you is to post data we can work with rightaway, so CREATE TABLE statement, and INSERT INTO statement. So: not output, but statements...
    Since I'm in a good mood (we're in the semi finals ;) ), here's an example of how you should post your data:
    create table a1 as
    select 1 quest_code, 'Fibrostenotic' quest_desc from dual union
    select 2, 'Inflammatory' from dual union
    select 3, 'Int Penetrating/Perforating' from dual union
    select 4, 'Perianal Perforating Disease' from dual union
    select 5, 'Uc Like' from dual union
    select 6, 'Flare Of Disease' from dual union
    select 7, 'Immunosuppressive Tx' from dual union
    select 8, 'Iv Therapy' from dual union
    select 9, 'Stool Consistency' from dual union
    select 10, 'Urgency' from dual union
    select 11, 'Stool Frequency' from dual union
    select 12, 'Bleeding' from dual union
    select 13, 'Adb Pain' from dual union
    select 14, 'Fever/Chills' from dual union
    select 15, 'Fistula' from dual union
    select 16, 'Obstructive Sx' from dual union
    select 17, 'Extraintestinal Sx' from dual union
    select 18, 'Steroid Dependent' from dual union
    select 19, 'Sibo' from dual union
    select 20, 'Osteoporosis' from dual union
    select 21, 'Osteopenia' from dual union
    select 22, 'Growth' from dual union
    select 23,  'Other' from dual;
    create table a2 as
    select 1 quest_code, 'U' quest_response, 88 user_id from dual union
    select 2, 'U', 88 from dual union
    select 3, 'U', 88 from dual union
    select 4, 'U', 88 from dual union
    select 5, 'U', 88 from dual;
    create table a3 as
    select 'testuserb' user_name, 88 user_id from dual;Posted like that, we can copy+paste and try to help you rightaway instead of waisting time formatting, putting quotes right etc. etc.
    Also use the {noformat}{noformat} tag when you post an example.
    That way it will stay formatted and indented.
    So, when you type: {noformat}select *
    from dual;{noformat}
    it will appear as: select *
    from dual;when you post it.
    Finally, perhaps you could try something like this:SQL> select a1.quest_desc
    2 , a2.quest_response
    3 , case
    4 when (select a3.user_id
    5 from a3
    6 where a3.user_id = a2.user_id) is not null
    7 then (select a3.user_id
    8 from a3
    9 where a3.user_id = a2.user_id)
    10 else (select a3.user_id
    11 from a3
    12 where a3.user_name = 'testuserb')
    13 end user_id
    14 from a1
    15 , a2
    16 where a1.quest_code = a2.quest_code(+);
    QUEST_DESC Q USER_ID
    Fibrostenotic U 88
    Inflammatory U 88
    Int Penetrating/Perforating U 88
    Perianal Perforating Disease U 88
    Uc Like U 88
    Iv Therapy 88
    Fistula 88
    Bleeding 88
    Osteopenia 88
    Sibo 88
    Urgency 88
    Extraintestinal Sx 88
    Steroid Dependent 88
    Immunosuppressive Tx 88
    Fever/Chills 88
    Obstructive Sx 88
    Stool Consistency 88
    Adb Pain 88
    Other 88
    Growth 88
    Osteoporosis 88
    Stool Frequency 88
    Flare Of Disease 88
    23 rows selected.

  • Pls help to rewrite the query in another method .

    Insert into bl_voyage_details (BVD_COMPANY,BVD_REFERENCE,BVD_SERIAL,BVD_CARRIER,BVD_VESSEL,BVD_VOY,BVD_LOCATION,BVD_TYPE,BVD_CRT_BY,BVD_CRT_ON,
    BVD_UPD_BY,BVD_UPD_ON,BVD_STATUS,BVD_STATUS_DATE,BVD_STATUS_BY )
    Values (Select bdl_company,bdl_reference,
    *(select nvl(max(bvd_serial),0)+1 from bl_voyage_details)*
    ,bdl_carrier,bdl_vessel,bdl_voy,bdl_location,bdl_type,user,sysdate,user,'0',sysdate,sysdate from bl_details)
    Insert into bl_voyage_details (BVD_COMPANY,BVD_REFERENCE,BVD_SERIAL,BVD_CARRIER,BVD_VESSEL,BVD_VOY,BVD_LOCATION,BVD_TYPE,BVD_CRT_BY,BVD_CRT_ON,
    BVD_UPD_BY,BVD_UPD_ON,BVD_STATUS,BVD_STATUS_DATE,BVD_STATUS_BY )
    Values (Select bdl_company,bdl_reference,
    *(select nvl(max(bvd_serial),0)+1 from bl_voyage_details where (BVD_COMPANY,BVD_REFERENCE)in (bdl_company,bdl_reference)* )
    ,bdl_carrier,bdl_vessel,bdl_voy,bdl_location,bdl_type,user,sysdate,user,'0',sysdate,sysdate from bl_details)
    Edited by: Rinz on Apr 27, 2010 3:57 PM
    Edited by: Rinz on Apr 27, 2010 3:57 PM

    Seems related to your previous question ( Procedure creation )
    Is there any reason why you couldn't just use a sequence:
    insert into bl_voyage_details
    (bvd_company,
      bvd_reference,
      bvd_serial,
      bvd_carrier,
      bvd_vessel,
      bvd_voy,
      bvd_location,
      bvd_type,
      bvd_crt_by,
      bvd_crt_on,
      bvd_upd_by,
      bvd_upd_on,
      bvd_status,
      bvd_status_date,
      bvd_status_by
    select bdl_company,
           bdl_reference,
           some_sequence.nextval,  --<< use a sequence
           bdl_carrier,
           bdl_vessel,
           bdl_voy,
           bdl_location,
           bdl_type,
           user,
           sysdate,
           user,
           sysdate,
           '0',
           sysdate,
           sysdate
    from   bl_details;Also:
    To post formatted code, put the {noformat} {noformat}- tag before and after your examples.
    When you post:
    {noformat} select *
    from dual;
    {noformat}
    it will appear as: select *
    from dual;
    on the forum.
    The FAQ will tell you more: http://forums.oracle.com/forums/help.jspa                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help with rewriting the query for faster execution.

    Hello Everybody,
    We are on Version
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    I am trying to get data from tab1 where col8 is equal to ' ' at the same time If we 2 or 3 records matched on col1 and col2 with different dates(col3) i am only interested in getting one record with the least date....
    Here is the sample data...
    Col1 col2 col3 COL4 COl5 Col6 COL7 COL8 COL9
    12 1 17-JAN-13 1 5 7 9 1233333 25
    10 2 16-JAN-13 2 5 7 9 1233333 25
    10 2 14-JAN-13 2 5 7 9 1233333 25
    16 6 16-JAN-13 6 5 7 9 1233333 28
    16 6 09-OCT-12 5 5 7 9 1233333 29
    16 6 15-JAN-13 6 5 7 9 1233333 28
    17 5 09-OCT-12 5 5 7 9 1233333 29
    17 5 16-JAN-13 6 5 7 9 1233333 28
    17 5 10-OCT-12 5 5 7 9 1233333 29
    I am expecting output like this only should pull records...with min or least date
    Col1 col2 col3 COL4 COl5 Col6 COL7 COL8 COL9
    10 2 14-JAN-13 2 5 7 9 1233333 25
    16 6 09-OCT-12 5 5 7 9 1233333 29
    17 5 09-OCT-12 5 5 7 9 1233333 29
    Below query works and we have close to billion rows in a table but the where clause would filter out to 100 mill records.
    and i am trying to see if there is an effecient way of writing this....we have an index on COL3.
    Select col1,col2,col3,col4,col5,col6,col7,col8,col9 from(Selct of.,row_number() over (partition by col1,col2 order by col3 asc) as rnk
    from tabl of where of.col8 = '1233333') where rnk = 1*
    From the above query i get the below explain plan
    | Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | Pstart| Pstop |
    | 0 | SELECT STATEMENT | | 1016M| 118G| | 13M (2)| 45:46:43 | | |
    |* 1 | VIEW | | 1016M| 118G| | 13M (2)| 45:46:43 | | |
    |* 2 | WINDOW SORT PUSHED RANK| | 1016M| 43G| 64G| 13M (2)| 45:46:43 | | |
    | 3 | PARTITION LIST SINGLE | | 1016M| 43G| | 1878K (3)| 06:15:47 | 4 | 4 |
    | 4 | TABLE ACCESS FULL | TAB1 | 1016M| 43G| | 1878K (3)| 06:15:47 | 4 | 4 |
    Predicate Information (identified by operation id):
    1 - filter("RNK"=1)
    2 - filter(ROW_NUMBER() OVER ( PARTITION BY "COL1","COl2" ORDER BY "COl3")<=1)
    17 rows selected
    Thanks In Advance!
    Edited by: 983949 on Jan 24, 2013 11:50 AM

    983949 wrote:
    Hello Everybody,
    I am trying to get data from tab1 where col8 is equal to ' ' at the same time.
    If we 2 or 3 records matched on col1 and col2 with different dates(col3)
    i am only interested in getting one record with the least date...
    Below query works and we have close to billion rows in a table but the where clause would filter out to 100 mill records.
    and i am trying to see if there is an effecient way of writing this....we have an index on COL3.
    Select col1,col2,col3,col4,col5,col6,col7,col8,col9
    from(Selct of.*,row_number() over (partition by col1,col2 order by col3 asc) as rnk
    from tabl of where of.col8 = '1233333') where rnk = 1
    Thanks In Advance!How do I ask a question on the forums?
    SQL and PL/SQL FAQ

  • Please help rewrite the query

    Hi ,
    Below query is taking more time (4mins) for 41 rows returning and there is no full table scan .Can some one help to rewrite the query.
    SELECT
              esma.candidate AS candidate_additional_sample,
              ccr.raw_mark,
              ccr.split_session_year AS year,
              ccr.split_session_month AS month,
              ccr.paper_code,
              ccr.assessment_school AS school_code,
              get_cand_session_number(ccr.split_session_year,ccr.split_session_month,ccr.candidate) AS candidate_session_number,
              ccr.candidate AS candidate_code,
              c.firstname AS candidate_firstname,
              c.lastname AS candidate_lastname,
              ema.moderator_code,
              ema.examiner_code,
              csr.self_taught
             FROM
              ibis.candidate_component_reg ccr
            INNER JOIN ibis.candidate_examiner_allocation cea
               ON ccr.split_session_year= cea.year
              AND ccr.split_session_month=cea.month
              AND ccr.assessment_school=cea.assessment_school
              AND ccr.paper_code= cea.paper_code
              AND ccr.candidate     =        cea.candidate
            INNER JOIN ibis.examination_paper ep
              ON ccr.split_session_year= ep.year
              AND ccr.split_session_month=ep.month
              AND ccr.paper_code=ep.paper_code
            INNER JOIN ibis.examiner_moderator_allocation ema
              ON ema.year =cea.year
              AND ema.month =cea.month
              AND ema.no_lang_code=ep.no_lang_code
              AND ema.examiner_code=cea.examiner_code
              AND ema.year =ccr.split_session_year
              AND ema.month =ccr.split_session_month
            INNER JOIN ibis.candidate_subject_registration csr
              ON ccr.split_session_year=csr.year
              AND ccr.split_session_month=csr.month
              AND ccr.main_school=csr.main_school
              AND ccr.candidate=csr.candidate
              AND ccr.subject=csr.subject
              AND ccr.subject_option=csr.subject_option
              AND ccr.lvl=csr.lvl
              AND ccr.language=csr.language 
            INNER JOIN ibis.candidate c
              ON ccr.candidate=c.candidate
            LEFT OUTER JOIN  ibis.exam_sample_mark_additional esma
              ON ccr.split_session_year = esma.year
              AND ccr.split_session_month  = esma.month
              AND ep.no_lang_code = esma.nolang_code
              AND ccr.candidate = esma.candidate
            WHERE
                  ccr.split_session_year=:v_year
              AND ccr.split_session_month=:v_month
              AND ccr.subject=:v_subject
              AND ccr.subject_option=nvl(:v_subject_option,ccr.subject_option)
              AND ccr.language=nvl(:v_language, ccr.language)
              AND ccr.component=:v_component
              AND ccr.lvl=:v_lvl
              AND ccr.raw_mark IS NOT NULL          
              AND cea.examiner_code  = :v_examiner_code
              AND ((ccr.sampled='Y'
                      AND csr.self_taught='N'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND sc.assessment_type='INTERNAL'
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND NOT EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y')
                      AND NOT EXISTS (SELECT 1 FROM ibis.school_sample_mark ssm
                                      WHERE ssm.year= ccr.split_session_year
                                        AND ssm.month  = ccr.split_session_month
                                        AND ssm.paper_code  = ccr.paper_code
                                        AND ssm.candidate =ccr.candidate
                                        AND ssm.examiner_sample = 'Y'))
                  OR (ccr.sampled='N'
                      AND csr.self_taught='Y'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND NOT EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y'))
                  OR (ccr.sampled='N'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y')));
    explain plan
    line 1: SQLPLUS Command Skipped: set linesize 130
    line 2: SQLPLUS Command Skipped: set pagesize 0
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    Plan hash value: 2594643366                                                                                                                                                                                                                                                                                 
    | Id  | Operation                             | Name                           | Rows  | Bytes | Cost (%CPU)| Time     |                                                                                                                                                                                    
    |   0 | SELECT STATEMENT                      |                                |     2 |  1036 |    34   (3)| 00:00:01 |                                                                                                                                                                                    
    |*  1 |  FILTER                               |                                |       |       |            |          |                                                                                                                                                                                    
    |*  2 |   HASH JOIN OUTER                     |                                |     2 |  1036 |    34   (3)| 00:00:01 |                                                                                                                                                                                    
    |   3 |    VIEW                               |                                |     2 |   974 |    32   (0)| 00:00:01 |                                                                                                                                                                                    
    |   4 |     CONCATENATION                     |                                |       |       |            |          |                                                                                                                                                                                    
    |*  5 |      FILTER                           |                                |       |       |            |          |                                                                                                                                                                                    
    |*  6 |       TABLE ACCESS BY INDEX ROWID     | CANDIDATE_SUBJECT_REGISTRATION |     1 |    58 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |   7 |        NESTED LOOPS                   |                                |     1 |   485 |    16   (0)| 00:00:01 |                                                                                                                                                                                    
    |   8 |         NESTED LOOPS                  |                                |     1 |   427 |    13   (0)| 00:00:01 |                                                                                                                                                                                    
    |   9 |          NESTED LOOPS                 |                                |     1 |   357 |    11   (0)| 00:00:01 |                                                                                                                                                                                    
    |  10 |           NESTED LOOPS                |                                |     1 |   129 |     8   (0)| 00:00:01 |                                                                                                                                                                                    
    |  11 |            NESTED LOOPS               |                                |     1 |    80 |     5   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 12 |             INDEX RANGE SCAN          | PK_EXAMINER_MODERATOR_ALLOC    |     1 |    39 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 13 |             INDEX RANGE SCAN          | RFL_EP1                        |     1 |    41 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  14 |            TABLE ACCESS BY INDEX ROWID| CANDIDATE_EXAMINER_ALLOCATION  |     1 |    49 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 15 |             INDEX RANGE SCAN          | CANDIDATE_ALLOCATION_EXAMINER  |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 16 |           TABLE ACCESS BY INDEX ROWID | CANDIDATE_COMPONENT_REG        |     1 |   228 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 17 |            INDEX RANGE SCAN           | SPLIT_SESSION_CANDIDATE        |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  18 |          TABLE ACCESS BY INDEX ROWID  | CANDIDATE                      |     1 |    70 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 19 |           INDEX UNIQUE SCAN           | CANDIDATE_PK                   |     1 |       |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 20 |         INDEX RANGE SCAN              | Y_M_CAND_SUBJ_LVL_OPTION       |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 21 |      FILTER                           |                                |       |       |            |          |                                                                                                                                                                                    
    |* 22 |       TABLE ACCESS BY INDEX ROWID     | CANDIDATE_SUBJECT_REGISTRATION |     1 |    58 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |  23 |        NESTED LOOPS                   |                                |     1 |   485 |    16   (0)| 00:00:01 |                                                                                                                                                                                    
    |  24 |         NESTED LOOPS                  |                                |     1 |   427 |    13   (0)| 00:00:01 |                                                                                                                                                                                    
    |  25 |          NESTED LOOPS                 |                                |     1 |   357 |    11   (0)| 00:00:01 |                                                                                                                                                                                    
    |  26 |           NESTED LOOPS                |                                |     1 |   129 |     8   (0)| 00:00:01 |                                                                                                                                                                                    
    |  27 |            NESTED LOOPS               |                                |     1 |    80 |     5   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 28 |             INDEX RANGE SCAN          | PK_EXAMINER_MODERATOR_ALLOC    |     1 |    39 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 29 |             INDEX RANGE SCAN          | RFL_EP1                        |     1 |    41 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  30 |            TABLE ACCESS BY INDEX ROWID| CANDIDATE_EXAMINER_ALLOCATION  |     1 |    49 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 31 |             INDEX RANGE SCAN          | CANDIDATE_ALLOCATION_EXAMINER  |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 32 |           TABLE ACCESS BY INDEX ROWID | CANDIDATE_COMPONENT_REG        |     1 |   228 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 33 |            INDEX RANGE SCAN           | SPLIT_SESSION_CANDIDATE        |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  34 |          TABLE ACCESS BY INDEX ROWID  | CANDIDATE                      |     1 |    70 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 35 |           INDEX UNIQUE SCAN           | CANDIDATE_PK                   |     1 |       |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 36 |         INDEX RANGE SCAN              | Y_M_CAND_SUBJ_LVL_OPTION       |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 37 |    INDEX RANGE SCAN                   | EXAM_SAMP_MARK_ADD_IOT_PK      |    36 |  1116 |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 38 |   TABLE ACCESS BY INDEX ROWID         | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 39 |    INDEX RANGE SCAN                   | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 40 |    TABLE ACCESS BY INDEX ROWID        | SCHOOL_SAMPLE_MARK             |     1 |    34 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 41 |     INDEX RANGE SCAN                  | CAND_PAPER_YEAR_MONTH          |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 42 |     TABLE ACCESS BY INDEX ROWID       | SUBJECT_COMPONENT              |     1 |    96 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 43 |      INDEX RANGE SCAN                 | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 44 |      TABLE ACCESS BY INDEX ROWID      | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 45 |       INDEX RANGE SCAN                | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 46 |       TABLE ACCESS BY INDEX ROWID     | SUBJECT_COMPONENT              |     1 |    87 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 47 |        INDEX RANGE SCAN               | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 48 |        TABLE ACCESS BY INDEX ROWID    | SUBJECT_COMPONENT              |     1 |    87 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 49 |         INDEX RANGE SCAN              | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 50 |         TABLE ACCESS BY INDEX ROWID   | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 51 |          INDEX RANGE SCAN             | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
      Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       1 - filter("from$_subquery$_011"."SAMPLED"='Y' AND "from$_subquery$_011"."SELF_TAUGHT"='N' AND  NOT EXISTS                                                                                                                                                                                               
                  (SELECT /*+ */ 0 FROM "IBIS"."CW_PORTFOLIO_TEMPLATE" "CPT" WHERE "CPT"."COMPONENT"=:B1 AND                                                                                                                                                                                                    
                  "CPT"."SUBJECT_OPTION"=:B2 AND "CPT"."SUBJECT"=:B3 AND "CPT"."MONTH"=:B4 AND "CPT"."YEAR"=:B5 AND                                                                                                                                                                                             
                  "CPT"."COMBINED"='Y') AND  NOT EXISTS (SELECT /*+ */ 0 FROM "IBIS"."SCHOOL_SAMPLE_MARK" "SSM" WHERE                                                                                                                                                                                           
                  "SSM"."MONTH"=:B6 AND "SSM"."YEAR"=:B7 AND "SSM"."PAPER_CODE"=:B8 AND "SSM"."CANDIDATE"=:B9 AND                                                                                                                                                                                               
                  "SSM"."EXAMINER_SAMPLE"='Y') AND  EXISTS (SELECT /*+ */ 0 FROM "IBIS"."SUBJECT_COMPONENT" "SC" WHERE                                                                                                                                                                                          
                  "SC"."COMPONENT"=:B10 AND "SC"."SUBJECT_OPTION"=:B11 AND "SC"."LANGUAGE"=:B12 AND "SC"."LVL"=:B13 AND                                                                                                                                                                                         
                  "SC"."SUBJECT"=:B14 AND "SC"."MONTH"=:B15 AND "SC"."YEAR"=:B16 AND "SC"."PAPER_CODE"=:B17 AND                                                                                                                                                                                                 
                  "SC"."ASSESSMENT_METHOD_ID"=11 AND "SC"."ASSESSMENT_TYPE"='INTERNAL') OR "from$_subquery$_011"."SAMPLED"='N'                                                                                                                                                                                  
                  AND "from$_subquery$_011"."SELF_TAUGHT"='Y' AND  NOT EXISTS (SELECT /*+ */ 0 FROM                                                                                                                                                                                                             
                  "IBIS"."CW_PORTFOLIO_TEMPLATE" "CPT" WHERE "CPT"."COMPONENT"=:B18 AND "CPT"."SUBJECT_OPTION"=:B19 AND                                                                                                                                                                                         
                  "CPT"."SUBJECT"=:B20 AND "CPT"."MONTH"=:B21 AND "CPT"."YEAR"=:B22 AND "CPT"."COMBINED"='Y') AND  EXISTS (SELECT                                                                                                                                                                               
                  /*+ */ 0 FROM "IBIS"."SUBJECT_COMPONENT" "SC" WHERE "SC"."COMPONENT"=:B23 AND "SC"."SUBJECT_OPTION"=:B24 ANDEdited by

    Can you please post the following scripts:
    1. Tables structure (with all indexes & constraints)
    2. Tables data
    3. SQL trace file
    possibly everything that one can need to regenerate the scenario on his own DB...
    OR
    spend some time with Oracle Docs on Performance Tuning and then resolve it yourself.
    Regards,
    Ankit Rathi
    http://theoraclelog.blogspot.in

  • Rewrite the query with out joins and group by

    Hi,
    This was an interview question.
    Table Names: bookshelf_checkout
    bookshelf
    And the join condition between these two tables is title
    We need to rewrite below query without using join condition and group by clause ?
    SELECT b.title,max(bc.returned_date - bc.checkout_date) "Most Days Out"
               FROM bookshelf_checkout bc,bookshelf b
               WHERE bc.title(+)=b.title
               GROUP BY b.title;When I was in college, I read that most of the SELECT statements can be replaced by basic SQL operations (SET OPERATORS). Now I am trying to rewrite the query with SET operators but not able to get the exact result.
    Kindly help me on this.
    Thanks,
    Suri

    Something like this?
      1  WITH books AS (
      2  SELECT 'title 1' title FROM dual UNION ALL
      3  SELECT 'title 2' FROM dual UNION ALL
      4  SELECT 'title 3' FROM dual ),
      5  bookshelf AS (
      6  SELECT 'title 1' title, DATE '2012-05-01' checkout_date, DATE '2012-05-15' returned_date FROM dual UNION ALL
      7  SELECT 'title 1' title, DATE '2012-05-16' checkout_date, DATE '2012-05-20' returned_date FROM dual UNION ALL
      8  SELECT 'title 2' title, DATE '2012-04-01' checkout_date, DATE '2012-05-15' returned_date FROM dual )
      9  SELECT bs.title, MAX(bs.returned_date - bs.checkout_date) OVER (PARTITION BY title) FROM bookshelf bs
    10  UNION
    11  (SELECT b.title, NULL FROM books b
    12  MINUS
    13* SELECT bs.title, NULL FROM bookshelf bs)
    SQL> /
    TITLE   MAX(BS.RETURNED_DATE-BS.CHECKOUT_DATE)OVER(PARTITIONBYTITLE)
    title 1                                                           14
    title 2                                                           44
    title 3Lukasz

  • Need help in refining the query

    Hello Experts,
    Need your help in refining the query further more.
    table structure 
    Mskey  Col A Col B
    1   empno [20141127-20151128]1234
    1   empno [20151201-99991231]232544
    1   salutation [20141127-99991231]Mrs
    1   salutation [20151127-99991231]Mr
    2   empno [20141127-20151128]1234
    2   empno [20151201-99991231]232544
    2   salutation [20141127-99991231]Mrs
    2   salutation [20151127-99991231]Mr
    My requirement is to find the list of overlapping records based on the dates
    user details may be varying from time to time as new data would be pushed through HR systems to identity store via an interface.
    The job is getting failed whenever there is any overlapping with dates. So we proactively decided to schedule a job in this regards which runs weekly and would let us know for which and all the users there is overlapping dates are there, so that we can send the list to HR team for pushing new data.
    Overlapping Issue Example:
    The users employee id for an year it is 1234 and later he moved to another department and his employee id got changed and it became 2345 remaining all details are same. So the HR systems send the data for this user as empno - [20141127-20151128]1234 and empno - [20151201-99991231]232544
    it means from 20141127 to 20151128 his employee no is 1234 and from 20151201 to 99991231 his employee would be 2345.
    This is a correct case and the tool would accept this data.
    the below cases are invald
    Case 1: 1 salutation [20141127-99991231]Mrs 1 salutation [20151127-99991231]Mr
    Case 2: 2 salutation [20141127-99991231]Mrs 2 salutation [20141127-99991231]Mr
    So we wanted to find these overlapping records from tables.
    My Query:
    I am able to successfully write query for the case 2 type but unable to write for case1.
    select id,colA
    count(left(ColB,CHARINDEX(']',ColB))) as 'Count'
    from tblA with (nolock)
    where id in (Select distinct id from tblb with (nolock))
    group by id, cola,left(ColB,CHARINDEX(']',ColB))
    having count(left(ColB,CHARINDEX(']',ColB)))>1

    Finally got the required answer with the below query
    WITH Cte AS
    SELECT ID,ColA,ColB,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN,
    CAST(SUBSTRING(ColB,2,CHARINDEX('-',ColB)-2) AS DATE) AS StartDT,
    CAST(SUBSTRING(ColB,CHARINDEX('-',ColB)+1,8) AS DATE)  AS EndDT  FROM TblA
    SELECT c1.ID, c1.ColA,c1.ColB
    FROM Cte c1 JOIN Cte c2
    ON c1.RN != c2.RN
    AND c1.ID=c2.ID
    AND c1.ColA=c2.ColA
    AND (c1.StartDT BETWEEN c2.StartDT AND c2.EndDT OR c2.StartDT BETWEEN c1.StartDT AND c1.EndDT )

  • Need a help to write the query

    Hi,
    I need a small help to write the query.
    I have a table contains couponid,coupon,createdate,expirationdate,assigndate from couponday table
    i want to write the query to select the coupon whose Expiry date in the table is NOT within 30 days.
    Thanks in advance

    Hi,
    user586 wrote:
    i want to write the query to select the coupon whose Expiry date in the table is NOT within 30 days.If you mean expirationdate (datatype: DATE) is not within 30 days (past or future) of run time, then:
    SELECT  coupon          -- or whatever columns you want
    FROM    table_x
    WHERE   expirationdate  NOT BETWEEN  SYSDATE - 30
                                AND      SYSDATE + 30
    ;

  • How to rewrite the query

    hi ,
    Actual i write the query like this , and run this query in sql developer ,
    it will take more than 15 mins
    alloc_details table -- 2 lac records
    doc_details -- 2 lac records
    query :
    SELECT
         a.activity
    ,      sum( a.lamt ) lamt
    ,      sum( a.lamt ) camt
    FROM
         alloc_detail a
    WHERE
         a.alc_code <>'JOB'
    And      a.alc_value is not null
    And      EXISTS ( SELECT
                   distinct b.doc_no
         FROM
                   doc_detail b
         WHERE
                   a.org=b.org
         And      a.doc_no=b.doc_no
         And      a.doc_type=b.doc_type
         And      ( b.dr_act_code='11111' OR b.cr_act_code='111111')
         And      ( ( trunc( b.doc_date ) >='01-jan-08' ) )
         And      ( ( trunc( b.doc_date ) <= '31-jan-08' ) )
    GROUP BY
         a.alc_value
    Anyother way to rewrite the query .

    Is this query working? a.activity seems to be a "not a group by expression"
    select a.activity,sum(a.lamt) lamt,sum(a.lamt) camt  /* 2 times same sum - a typo ? */
      from alloc_detail a
    where a.alc_code != 'JOB'      /* not equal presumed */
       and a.alc_value is not null
       and exists(select distinct b.doc_no
                    from doc_detail b
                   where a.org = b.org
                     and a.doc_no = b.doc_no
                     and a.doc_type = b.doc_type
                     and (b.dr_act_code = '11111' or b.cr_act_code = '111111')
                     and trunc(b.doc_date) >= '01-jan-08'
                     and trunc(b.doc_date) <= '31-jan-08'
    group by a.alc_valuehow about applying predicates first
    select a.alc_value,sum(a.lamt) lamt,sum(a.camt) camt
      from (select alc_value,lamt,camt,org,doc_no,doc_type
              from alloc_detail
             where alc_code != 'JOB'
               and alc_value is not null
           ) a,
           (select distinct org,doc_no,doc_type
              from doc_detail
             where doc_date >= to_date('01-jan-08','dd-mon-rr')
               and doc_date <= to_date('31-jan-08','dd-mon-rr') + 1 - 1/24/60/60
               and (dr_act_code = '11111' or cr_act_code = '111111')
           ) b
    where a.org = b.org
       and a.doc_no = b.doc_no
       and a.doc_type = b.doc_type
    group by a.alc_valueRegards
    Etbin

  • Help with performance SQL  tuning - Rewriting the query

    Hi
    I have serious performance issues with some 8 update queries
    These were earlier taking 5 mins . Now taking 2.5 hours
    This is one of the culprit UPDATE statement (These are 7 such other update statements on different tables but same logic)
    We have change the update to MERGE and used PARALLEL hints but have not got desired results
    There are appropriate indexes on the tables
    Is there a way to rewrite the UPDATE statement in a better way to improve the performance
    update TABLE_dob
    set key_act =
    (select skey from table_subs
    where sub_act = sub_num)
    where exists
    (select 1 from table_subs
    where sub_act = sub_num);
    Table_DOB has 37 million records
    Table_subs has 20 million records

    aashoo_5 wrote:
    Hi
    I have serious performance issues with some 8 update queries
    These were earlier taking 5 mins . Now taking 2.5 hours
    This is one of the culprit UPDATE statement (These are 7 such other update statements on different tables but same logic)
    We have change the update to MERGE and used PARALLEL hints but have not got desired results
    There are appropriate indexes on the tables
    Is there a way to rewrite the UPDATE statement in a better way to improve the performance
    update TABLE_dob
    set key_act =
    (select skey from table_subs
    where sub_act = sub_num)
    where exists
    (select 1 from table_subs
    where sub_act = sub_num);
    Table_DOB has 37 million records
    Table_subs has 20 million recordsThread: HOW TO: Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting

  • Kindly help with rewriting the foll. query in a better way

    IS there a better way of writing the foll query:
    When I have 12,50,00,000 rows in Fact Table, the query is unable to execute. I use more than 200GB of temporary space. But I still get Temp Tablespace Full Error:
    --Foll WITH Clause is to calculate Sum of Debit-Credit to calculate BLNC acc. to Group By values
    WITH crnt_blnc_set
    AS ( SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id AS crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.acntng_entry_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    DECODE (
    f.pstng_typ,
    'Credit', f.pstng_amnt,
    0))
    - SUM (
    DECODE (
    f.pstng_typ,
    'Debit', f.pstng_amnt,
    0))
    AS blnc
    FROM FactTable f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.pstng_crncy_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.acntng_entry_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt),
    --Foll WITH Clause calculates Min and Max Date Ids for the Group By conditions as mentioned
    min_mx_dt
    AS ( SELECT /*+parallel(32)*/
    f.hrarchy_dmn_id AS hrarchy_dmn_id,
    f.prduct_dmn_id AS prduct_dmn_id,
    f.crncy_dmn_id AS crncy_dmn_id,
    f.acnt_dmn_id AS acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS txn_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    MIN (f.val_dt_dmn_id) AS min_val_dt,
    GREATEST (MAX (f.val_dt_dmn_id), 2689) AS max_val_dt
    FROM crnt_blnc_set f
    GROUP BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ),
    /*Foll WITH Clause has a Cartesian Join on date_dmn to populate missing entries
    This requirement is because if we have a distinct row for
    hrarchy_dmn_id,
    prduct_dmn_id,
    crncy_dmn_id,
    acnt_dmn_id,
    txn_id,
    txn_src,
    acntng_entry_typ Combination and If wehave a missing entry for that in the max date provided then we actually create those missing entries*/
    slctd_rcrds
    AS ( SELECT /*+ ordered use_nl(d) parallel(mx, 4) */
    mx.hrarchy_dmn_id AS hrarchy_dmn_id,
    mx.prduct_dmn_id AS prduct_dmn_id,
    mx.crncy_dmn_id AS crncy_dmn_id,
    mx.acnt_dmn_id AS acnt_dmn_id,
    mx.txn_id AS txn_id,
    mx.txn_src AS txn_src,
    mx.acntng_entry_typ AS acntng_entry_typ,
    d.date_value AS val_dt,
    d.date_dmn_id AS val_dt_dmn_id
    FROM min_mx_dt mx, date_dmn d
    WHERE mx.min_val_dt <= d.date_dmn_id
    AND mx.max_val_dt >= d.date_dmn_id
    --Foll. WITH clause actually has a outer Join with Firt With Clause to populate the values accordingly
    cmbnd_rcrds
    AS (
    SELECT /*+ USE_HASH(c) */ s.hrarchy_dmn_id AS hrarchy_dmn_id,
    s.prduct_dmn_id AS prduct_dmn_id,
    s.crncy_dmn_id AS crncy_dmn_id,
    s.acnt_dmn_id AS acnt_dmn_id,
    s.txn_id AS txn_id,
    s.txn_src AS txn_src,
    s.acntng_entry_typ AS acntng_entry_typ,
    s.val_dt_dmn_id AS val_dt_dmn_id,
    NVL (c.revsn_dt, s.val_dt) AS revsn_dt,
    NVL (c.blnc, 0) AS blnc,
    0 AS prvs_rcrd_ind
    FROM slctd_rcrds s, crnt_blnc_set c
    WHERE s.hrarchy_dmn_id = c.hrarchy_dmn_id(+)
    AND s.prduct_dmn_id = c.prduct_dmn_id(+)
    AND s.crncy_dmn_id = c.crncy_dmn_id(+)
    AND s.acnt_dmn_id = c.acnt_dmn_id(+)
    AND s.txn_id = c.txn_id(+)
    AND s.txn_src = c.txn_src(+)
    AND s.acntng_entry_typ = c.acntng_entry_typ(+)
    AND s.val_dt_dmn_id = c.val_dt_dmn_id(+))
    Select * from cmbnd_rcrds

    Thanks for the response Alfonso. I have tried that as well. But Create Table as Also uses Temp Storage till it's created. And that again gives the same error as well.
    Anyways I am now trying with a smaller set. This much piece gets executed in Half an hour but the next piece where we pivot the data is taking forever now.
    That piece is as follows:
    (SELECT /*+parallel(8)*/
    f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ
    ORDER BY d.date_value)
    AS crnt_blnc,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_mnth_num
    || d.fin_year_strt
    || d.fin_year_end
    ORDER BY d.date_value)
    / d.mnth_to_dt
    AS mtd_avg,
    SUM (
    blnc)
    OVER (
    PARTITION BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    d.fin_year_strt || d.fin_year_end
    ORDER BY d.date_value)
    / yr_to_dt
    AS ytd_avg,
    f.prvs_rcrd_ind AS prvs_rcrd_ind
    FROM cmbnd_rcrds f, thor_date_dmn d
    WHERE d.holidaY_ind = 0 AND f.val_dt_dmn_id = d.date_dmn_id)
    SELECT f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id AS txn_id,
    f.txn_src AS acntng_entry_src,
    f.acntng_entry_typ AS acntng_entry_typ,
    f.val_dt_dmn_id,
    f.revsn_dt,
    f.crnt_blnc,
    f.mtd_avg,
    f.ytd_avg,
    'EOD TB ETL' AS crtd_by,
    SYSTIMESTAMP AS crtn_dt,
    NULL AS mdfd_by,
    NULL AS mdfctn_dt
    FROM fnl_set f
    WHERE f.prvs_rcrd_ind = 0
    ORDER BY f.hrarchy_dmn_id,
    f.prduct_dmn_id,
    f.crncy_dmn_id,
    f.acnt_dmn_id,
    f.txn_id,
    f.txn_src,
    f.acntng_entry_typ,
    f.val_dt_dmn_id
    Any other way to pivot this?
    Also I am getting a lot of foll wait events:
    PX Deq Credit :Send blkd
    PX Deq :Table Q Normal
    Direct Path Write Temp
    And Direct Path Read Temp.

  • Someone help me,rewrite the SP using PL/SQL

    the following SP is written in T-SQL,now I want to rewrite it with PL/SQL,who can help me ? tks
    CREATE PROCEDURE dbo.TEST_Proc_Jerry_OB @CountDay Char(8)
    AS
    Declare @UserID varchar(50)
    Declare @Count int
    Declare @SuccCount int
    Declare @UnSuccCount int
    create table tbTEST_Proc_Jerry_OB (
    agentalias varchar(255),
    count1 int,
    count2 int,
    count3 int
    Set @UserID = 'kokuyo6'
    select @Count = count(*),
    @SuccCount = sum(case when DialFlag='0' then 1 else 0 end),
    @UnSuccCount = sum(case when DialFlag='0' then 0 else 1 end)
    from tbobcdrmast where
    left(starttime,8)=@CountDay
    and agentalias='kokuyo6'
    group by agentalias
    Order By AgentAlias
    Insert Into tbTEST_Proc_Jerry_OB Values(@UserID, @Count, @SuccCount ,@UnSuccCount)
    Select * From tbTEST_Proc_Jerry_OB
    drop table tbTEST_Proc_Jerry_OB
    GO

    Here you ara your answer. Take good care.Indeed, I would take extreme care. I don't even have to try and test this code to know it won't work.
    CREATE PROCEDURE PR_PROCEDIMIENTO(
    p_exit out SYS_REFCURSOR) So we've lost the input parameter, which has now gone down to be declared as a local variable, we're passing back a pointer to a ref cursor (which I didn't see in the original requirement) and we're missing the "AS" or "IS" keyword.
    >
    CountDay Char(8);
    UserID varchar(50);
    Contador integer;Good to see you changed the reserved "Count" variable name to something else.
    SuccCount integer;
    UnSuccCount integer;
    BEGIN
    EXECUTE IMMEDIATE('create goblal temporary table
    tbTEST_Proc_Jerry_OB (
    agentalias varchar(255),
    count1 integer,
    count2 integer,
    count3 integer) on commit delete rows');So you've opted for a global temporary table. Okay.
    UserID := 'kokuyo6';
    select count(*), sum(case when DialFlag='0' then 1
    else 0 end),
    sum(case when DialFlag='0' then 0 else 1 end)
    into Count, SuccCount, UnSuccCountWhoops there's that reserved "Count" variable. Forgot to rename it here I see.
    from tbobcdrmast where
    left(starttime,8)=CountDay
    and agentalias='kokuyo6'
    group by agentalias
    Order By AgentAlias;There's no need for the Order By on the query as the where clause has already restricted it to a single value of this anyway.
    >
    Insert Into tbTEST_Proc_Jerry_OB
    Values(UserID, @Count, @SuccCount ,@UnSuccCount)And this is valid syntax is it?
    How is it going to compile on a table that hasn't even been created yet because it gets created at run time?
    >
    open p_exit for Select * From
    tbTEST_Proc_Jerry_OB;So you open up the ref cursor to pass back out (not part of the original requirement)
    >
    EXECUTE IMMEDIATE('drop table
    tbTEST_Proc_Jerry_OB');And before you finish, you go and drop the global temporary table that you have a ref cursor open on. Duh!
    >
    END;

  • How can rewrite the Query using Analytical functions ?

    Hi,
    I have the SQL script as shown below ,
    SELECT cd.cardid, cd.cardno,TT.TRANSACTIONTYPECODE,TT.TRANSACTIONTYPEDESC DESCRIPTION,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'LOAD_ACH'
    THEN th.transactionamount
    END, 0)
    ) AS load_ach,
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'FUND_TRANSFER_RECEIVED'
    THEN th.transactionamount
    END,
    0
    ) AS Transfersin,
    ( SUM (NVL (CASE tt.transactiontypecode
    WHEN 'FTRNS'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'SEND_MONEY'
    THEN th.transactionamount
    END, 0)
    )) AS Transferout,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_ACH'
    THEN th.transactionamount
    END, 0)
    ) AS withdrawal_ach,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK'
    THEN th.transactionamount
    END, 0)
    ) AS withdrawal_check,
    ( SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_FEE'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'REJECTED_ACH_LOAD_FEE'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_ACH_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'REJECTED_ACH_LOAD_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'OVERDRAFT_FEE_REV'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'STOP_CHECK_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'LOAD_ACH_REV'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'OVERDRAFT_FEE'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'STOP_CHECK_FEE'
    THEN th.transactionamount
    END, 0)
    )) AS Fee,
    th.transactiondatetime
    FROM carddetail cd,
    transactionhistory th,
    transactiontype tt,
    (SELECT rmx_a.cardid, rmx_a.endingbalance prev_balance, rmx_a.NUMBEROFDAYS
    FROM rmxactbalreport rmx_a,
    (SELECT cardid, MAX (reportdate) reportdate
    FROM rmxactbalreport
    GROUP BY cardid) rmx_b
    WHERE rmx_a.cardid = rmx_b.cardid AND rmx_a.reportdate = rmx_b.reportdate) a
    WHERE th.transactiontypeid = tt.transactiontypeid
    AND cd.cardid = th.cardid
    AND cd.cardtype = 'P'
    AND cd.cardid = a.cardid (+)
    AND CD.CARDNO = '7116734387812758335'
    --AND TT.TRANSACTIONTYPECODE = 'FUND_TRANSFER_RECEIVED'
    GROUP BY cd.cardid, cd.cardno, numberofdays,th.transactiondatetime,tt.transactiontypecode,TT.TRANSACTIONTYPEDESC
    Ouput of the above query is :
    CARDID     CARDNO     TRANSACTIONTYPECODE     DESCRIPTION     LOAD_ACH     TRANSFERSIN     TRANSFEROUT     WITHDRAWAL_ACH     WITHDRAWAL_CHECK     FEE     TRANSACTIONDATETIME
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     3.75     0     0     0     0     21/09/2007 11:15:38 AM
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     272     0     0     0     0     05/10/2007 9:12:37 AM
    6005     7116734387812758335     WITHDRAWAL_ACH     Withdraw Funds via ACH     0     0     0     300     0     0     24/10/2007 3:43:54 PM
    6005     7116734387812758335     SEND_MONEY     Fund Transfer Sent     0     0     1     0     0     0     19/09/2007 1:17:48 PM
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     1     0     0     0     0     18/09/2007 7:25:23 PM
    6005     7116734387812758335     LOAD_ACH     Prepaid Deposit via ACH     300     0     0     0     0     0     02/10/2007 3:00:00 AM
    I want the output like for Load_ACH there should be one record etc.,
    Can any one help me , how can i rewrite the above query using analytical functions .,
    Sekhar

    Not sure of your requirements but this mayhelp reduce your code;
    <untested>
    SUM (
       CASE
       WHEN tt.transactiontypecode IN
          ('WITHDRAWAL_CHECK_FEE', 'REJECTED_ACH_LOAD_FEE', 'WITHDRAWAL_ACH_REV', 'WITHDRAWAL_CHECK_REV',
           'WITHDRAWAL_CHECK_FEE_REV', 'REJECTED_ACH_LOAD_FEE_REV', 'OVERDRAFT_FEE_REV','STOP_CHECK_FEE_REV',
           'LOAD_ACH_REV', 'OVERDRAFT_FEE', 'STOP_CHECK_FEE')
       THEN th.transactionamount
       ELSE 0) feeAlso, you might want to edit your post and use &#91;pre&#93; and &#91;/pre&#93; tags around your code for formatting.

Maybe you are looking for