Help plzz ---tune query

INSERT INTO EXCEPTIONS_LOG
SELECT control.effective_start_date,
control.employee_number,
' EMP_NO:' || control.employee_number ||
' DEPT_ID:'|| control.dept_id ||
' HOURLY_RATE'|| control.hourly_rate ||
' SALARY_EFF_DATE'|| control.salary_eff_date ||
' SAL MID' ||
HRUSERDT.get_table_value (c_business_group_id,
'SALARY_RANGES',
'MID',
control.dept_id,
g_sysdate)||
' SAL MAX' ||
HRUSERDT.get_table_value (c_business_group_id,
'SALARY_RANGES',
'MAX',
control.dept_id,
g_sysdate)||
'- WARNING SALARY RANGE - WARNING ' ,
'W'
FROM NMHR.nmhr_adp_control control
WHERE hourly_rate BETWEEN
HRUSERDT.get_table_value (c_business_group_id,
'SALARY_RANGES',
'MID',
control.dept_id,
g_sysdate)
AND HRUSERDT.get_table_value (c_business_group_id,
'SALARY_RANGES',
'MAX',
control.dept_id,
g_sysdate)
AND control.PERSON_ID IN
     (SELECT PERSON_ID
     FROM EMPLOYEE_WORK work
     WHERE work.NEED_RECORD_FLAG = 'Y');
This query is taking quite a lot of time more than 50 sec's can u please suggest a mofication , that would speed this up...
Thanks in Advance

What does the function do? Is it any more than a subquery? Is it deterministic?
Any this code sucks. Probably what you should do is apply subquery factoring by putting calls to HRUSERDT.get_table_value () for all values of control.dept_id into a WITH() clause.
Cheers, APC

Similar Messages

  • HELP TO TUNE THIS QUERY

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

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

  • Urgent help to tune sql

    Hi Team,
    Could u pls help me tune this query.I have generated explain plan.pls look into it
    select distinct cust.id customer_id, addr.addrfirstname||' '||addr.addrsurname cust_name,sub.substypename cust_type,
    addr.addrbigcity city, reverse(substr(reverse(ms.name),instr(reverse(ms.name),'-')+1)) cluster_name,
    pro.provincename state,mst.name circle,addr.addrpostcode pincode,
    decode(dev.serial_number,null,'NA',dev.serial_number) SC_SR_NO,hm.description model_desc1,
    dev1.serial_number STB_SR_NO,
    hm1.description model_desc2,
    ds.description dev_status,
    to_char(suh.real_date,'mm/dd/yyyy') activation_date,
    to_char(fa.prepaid_end_date,'mm/dd/yyyy') prepaid_end_date,
    to_char(fa.PREPAID_DISCONNECT_DATE,'mm/dd/yyyy') PREPAID_DISCONNECT_DATE,
    to_char(ad.contract_start_date,'mm/dd/yyyy') contract_start_date,
    ibs.full_name activated_by,
    (select max(to_char(create_datetime,'mm/dd/yyyy')) from businessdata.suhistor where sheventnr in (133,1133) and entity_id=ad.id and shsubscribernr=ad.customer_id) disconnection_date,
    ad.comm_product_id d2h_pack_id,
    cp.description D2H_Package,
    ads.id D2h_PackageStatusId,
    ads.name D2h_PackageStatus,
    suh.sheventnr event_no,se.name event_description
    from businessdata.suhistor suh,businessdata.agreement_detail ad,businessdata.ibs_user ibs,
    businessdata.system_event se,businessdata.address addr, businessdata.customer cust,
    businessdata.province pro,businessdata.market_segment ms,businessdata.market_segment_type mst,
    businessdata.software_per_ad spa,businessdata.device_agreement_detail dad, businessdata.device dev,
    businessdata.device_status ds,businessdata.hardware_model hm,businessdata.substype sub,businessdata.device_pairing dp
    ,businessdata.device dev1,businessdata.hardware_model hm1,businessdata.commercial_product cp,businessdata.agreement_detail_status ads, businessdata.financial_account fa
    where
    trunc(suh.real_date) < trunc(sysdate) and
    suh.sheventnr in (5229,108) and
    suh.shsubscribernr =ad.customer_id and
    suh.entity_id=ad.id and
    suh.shusernr=ibs.id and
    suh.sheventnr=se.id and
    ad.customer_id=addr.addrcustnr and
    addr.addrcustnr=cust.id and
    addr.addrprovincenumber= pro.provincenumber and
    addr.marketsegment_id=ms.id and
    ms.market_segment_type_id=mst.id and
    ad.id= spa.agreement_detail_id and
    spa.device_per_ad_id =dad.id and
    dad.technical_product_id in (1,null) and
    dad.device_id= dev.id(+) and
    dev.status_id= ds.id(+) and
    dev.model_id=hm.id(+) and
    dev.id=dp.paired_from_id(+) and
    cust.type_id=sub.subscribertype and
    dp.paired_to_id=dev1.id(+) and
    dev1.model_id=hm1.id(+) and
    ad.comm_product_id=cp.id and
    cp.category_id=1 and
    ad.status=ads.id and
    ad.customer_id=fa.customer_id
    order by cust.id
    explain plan*****************
    Plan hash value: 3107127273
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 426 | 14905 (1)| 00:02:59 |
    | 1 | SORT AGGREGATE | | 1 | 23 | | |
    |* 2 | TABLE ACCESS BY INDEX ROWID | SUHISTOR | 1 | 23 | 7 (15)| 00:00:01 |
    | 3 | BITMAP CONVERSION TO ROWIDS | | | | | |
    | 4 | BITMAP AND | | | | | |
    | 5 | BITMAP CONVERSION FROM ROWIDS | | | | | |
    |* 6 | INDEX RANGE SCAN | IDX_SUHISTOR_ENTITY_ID | 17 | | 3 (0)| 00:00:01 |
    | 7 | BITMAP CONVERSION FROM ROWIDS | | | | | |
    | 8 | SORT ORDER BY | | | | | |
    |* 9 | INDEX RANGE SCAN | KEY002SUHISTOR | 17 | | 3 (0)| 00:00:01 |
    | 10 | SORT UNIQUE | | 1 | 426 | 14904 (1)| 00:02:59 |
    | 11 | NESTED LOOPS | | 1 | 426 | 14903 (1)| 00:02:59 |
    | 12 | NESTED LOOPS | | 1 | 414 | 14902 (1)| 00:02:59 |
    | 13 | NESTED LOOPS | | 1 | 384 | 14901 (1)| 00:02:59 |
    | 14 | NESTED LOOPS | | 1 | 371 | 14900 (1)| 00:02:59 |
    | 15 | NESTED LOOPS | | 1 | 363 | 14898 (1)| 00:02:59 |
    | 16 | NESTED LOOPS | | 1 | 348 | 14897 (1)| 00:02:59 |
    | 17 | NESTED LOOPS OUTER | | 1 | 304 | 14894 (1)| 00:02:59 |
    | 18 | NESTED LOOPS OUTER | | 1 | 286 | 14893 (1)| 00:02:59 |
    | 19 | NESTED LOOPS OUTER | | 1 | 260 | 14891 (1)| 00:02:59 |
    | 20 | NESTED LOOPS | | 1 | 248 | 14889 (1)| 00:02:59 |
    | 21 | NESTED LOOPS OUTER | | 1 | 228 | 14888 (1)| 00:02:59 |
    | 22 | NESTED LOOPS OUTER | | 1 | 215 | 14887 (1)| 00:02:59 |
    | 23 | NESTED LOOPS OUTER | | 1 | 197 | 14886 (1)| 00:02:59 |
    | 24 | NESTED LOOPS | | 1 | 168 | 14884 (1)| 00:02:59 |
    | 25 | NESTED LOOPS | | 1 | 154 | 14882 (1)| 00:02:59 |
    | 26 | NESTED LOOPS | | 1 | 144 | 14879 (1)| 00:02:59 |
    | 27 | NESTED LOOPS | | 1 | 124 | 14876 (1)| 00:02:59 |
    | 28 | NESTED LOOPS | | 1 | 111 | 14875 (1)| 00:02:59 |
    | 29 | NESTED LOOPS | | 3 | 264 | 14872 (1)| 00:02:59 |
    | 30 | NESTED LOOPS | | 85 | 5270 | 14744 (1)| 00:02:57 |
    | 31 | INLIST ITERATOR | | | | | |
    | 32 | TABLE ACCESS BY INDEX ROWID| SYSTEM_EVENT | 2 | 70 | 3 (0)| 00:00:01 |
    |* 33 | INDEX UNIQUE SCAN | PK_SYSTEM_EVENT | 2 | | 2 (0)| 00:00:01 |
    |* 34 | TABLE ACCESS BY INDEX ROWID | SUHISTOR | 42 | 1134 | 11582 (1)| 00:02:19 |
    |* 35 | INDEX RANGE SCAN | SUHISTOR_EVENTNR_CRDATE_IDX | 13157 | | 3159 (1)| 00:00:38 |
    |* 36 | TABLE ACCESS BY INDEX ROWID | AGREEMENT_DETAIL | 1 | 26 | 2 (0)| 00:00:01 |
    |* 37 | INDEX UNIQUE SCAN | PK_AGREEMENT_DETAIL | 1 | | 1 (0)| 00:00:01 |
    |* 38 | TABLE ACCESS BY INDEX ROWID | COMMERCIAL_PRODUCT | 1 | 23 | 1 (0)| 00:00:01 |
    |* 39 | INDEX UNIQUE SCAN | PK_COMMERCIAL_PRODUCT | 1 | | 0 (0)| 00:00:01 |
    | 40 | TABLE ACCESS BY INDEX ROWID | AGREEMENT_DETAIL_STATUS | 1 | 13 | 1 (0)| 00:00:01 |
    |* 41 | INDEX UNIQUE SCAN | PK_AGREEMENT_DETAIL_STATUS | 1 | | 0 (0)| 00:00:01 |
    | 42 | TABLE ACCESS BY INDEX ROWID | FINANCIAL_ACCOUNT | 1 | 20 | 3 (0)| 00:00:01 |
    |* 43 | INDEX RANGE SCAN | FINACCT_CUSTOMERID_IDX | 1 | | 2 (0)| 00:00:01 |
    | 44 | TABLE ACCESS BY INDEX ROWID | SOFTWARE_PER_AD | 1 | 10 | 3 (0)| 00:00:01 |
    |* 45 | INDEX RANGE SCAN | SPAD_AGREEMENTDETAILID_IDX | 1 | | 2 (0)| 00:00:01 |
    |* 46 | TABLE ACCESS BY INDEX ROWID | DEVICE_AGREEMENT_DETAIL | 1 | 14 | 2 (0)| 00:00:01 |
    |* 47 | INDEX UNIQUE SCAN | PK_DEVICE_AGREEMENT_DETAIL | 1 | | 1 (0)| 00:00:01 |
    | 48 | TABLE ACCESS BY INDEX ROWID | DEVICE | 1 | 29 | 2 (0)| 00:00:01 |
    |* 49 | INDEX UNIQUE SCAN | PK_DEVICE | 1 | | 1 (0)| 00:00:01 |
    | 50 | TABLE ACCESS BY INDEX ROWID | HARDWARE_MODEL | 1 | 18 | 1 (0)| 00:00:01 |
    |* 51 | INDEX UNIQUE SCAN | PK_HARDWARE_MODEL | 1 | | 0 (0)| 00:00:01 |
    | 52 | TABLE ACCESS BY INDEX ROWID | DEVICE_STATUS | 1 | 13 | 1 (0)| 00:00:01 |
    |* 53 | INDEX UNIQUE SCAN | PK_DEVICE_STATUS | 1 | | 0 (0)| 00:00:01 |
    | 54 | TABLE ACCESS BY INDEX ROWID | IBS_USER | 1 | 20 | 1 (0)| 00:00:01 |
    |* 55 | INDEX UNIQUE SCAN | KEY001USRNAMES | 1 | | 0 (0)| 00:00:01 |
    |* 56 | INDEX RANGE SCAN | KEY012DEVICE_PAIRING | 1 | 12 | 2 (0)| 00:00:01 |
    | 57 | TABLE ACCESS BY INDEX ROWID | DEVICE | 1 | 26 | 2 (0)| 00:00:01 |
    |* 58 | INDEX UNIQUE SCAN | PK_DEVICE | 1 | | 1 (0)| 00:00:01 |
    | 59 | TABLE ACCESS BY INDEX ROWID | HARDWARE_MODEL | 1 | 18 | 1 (0)| 00:00:01 |
    |* 60 | INDEX UNIQUE SCAN | PK_HARDWARE_MODEL | 1 | | 0 (0)| 00:00:01 |
    | 61 | TABLE ACCESS BY INDEX ROWID | ADDRESS | 1 | 44 | 3 (0)| 00:00:01 |
    |* 62 | INDEX RANGE SCAN | KEY002ADDRESS | 1 | | 2 (0)| 00:00:01 |
    | 63 | TABLE ACCESS BY INDEX ROWID | PROVINCE | 1 | 15 | 1 (0)| 00:00:01 |
    |* 64 | INDEX UNIQUE SCAN | KEY001PROVINCE | 1 | | 0 (0)| 00:00:01 |
    | 65 | TABLE ACCESS BY INDEX ROWID | CUSTOMER | 1 | 8 | 2 (0)| 00:00:01 |
    |* 66 | INDEX UNIQUE SCAN | PK_CUCUSTNR1 | 1 | | 1 (0)| 00:00:01 |
    | 67 | TABLE ACCESS BY INDEX ROWID | SUBSTYPE | 1 | 13 | 1 (0)| 00:00:01 |
    |* 68 | INDEX UNIQUE SCAN | KEY001SUBSTYPE | 1 | | 0 (0)| 00:00:01 |
    | 69 | TABLE ACCESS BY INDEX ROWID | MARKET_SEGMENT | 1 | 30 | 1 (0)| 00:00:01 |
    |* 70 | INDEX UNIQUE SCAN | PK_MARKET_SEGMENT | 1 | | 0 (0)| 00:00:01 |
    | 71 | TABLE ACCESS BY INDEX ROWID | MARKET_SEGMENT_TYPE | 1 | 12 | 1 (0)| 00:00:01 |
    |* 72 | INDEX UNIQUE SCAN | PK_MARKET_SEGMENT_TYPE | 1 | | 0 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    2 - filter("SHEVENTNR"=133 OR "SHEVENTNR"=1133)
    6 - access("ENTITY_ID"=:B1)
    9 - access("SHSUBSCRIBERNR"=:B1)
    filter("SHSUBSCRIBERNR"=:B1)
    33 - access("SE"."ID"=108 OR "SE"."ID"=5229)
    34 - filter("SUH"."SHSUBSCRIBERNR" IS NOT NULL AND TRUNC(INTERNAL_FUNCTION("SUH"."REAL_DATE"))<TRUNC(SYSDATE@!))
    35 - access("SUH"."SHEVENTNR"="SE"."ID")
    filter("SUH"."SHEVENTNR"=108 OR "SUH"."SHEVENTNR"=5229)
    36 - filter("SUH"."SHSUBSCRIBERNR"="AD"."CUSTOMER_ID")
    37 - access("SUH"."ENTITY_ID"="AD"."ID")
    38 - filter("CP"."CATEGORY_ID"=1)
    39 - access("AD"."COMM_PRODUCT_ID"="CP"."ID")
    41 - access("AD"."STATUS"="ADS"."ID")
    43 - access("AD"."CUSTOMER_ID"="FA"."CUSTOMER_ID")
    45 - access("AD"."ID"="SPA"."AGREEMENT_DETAIL_ID")
    46 - filter("DAD"."TECHNICAL_PRODUCT_ID"=1 OR "DAD"."TECHNICAL_PRODUCT_ID"=TO_NUMBER(NULL))
    47 - access("SPA"."DEVICE_PER_AD_ID"="DAD"."ID")
    49 - access("DAD"."DEVICE_ID"="DEV"."ID"(+))
    51 - access("DEV"."MODEL_ID"="HM"."ID"(+))
    53 - access("DEV"."STATUS_ID"="DS"."ID"(+))
    55 - access("SUH"."SHUSERNR"="IBS"."ID")
    56 - access("DEV"."ID"="DP"."PAIRED_FROM_ID"(+))
    58 - access("DP"."PAIRED_TO_ID"="DEV1"."ID"(+))
    60 - access("DEV1"."MODEL_ID"="HM1"."ID"(+))
    62 - access("AD"."CUSTOMER_ID"="ADDR"."ADDRCUSTNR")
    64 - access("ADDR"."ADDRPROVINCENUMBER"="PRO"."PROVINCENUMBER")
    66 - access("ADDR"."ADDRCUSTNR"="CUST"."ID")
    68 - access("CUST"."TYPE_ID"="SUB"."SUBSCRIBERTYPE")
    70 - access("ADDR"."MARKETSEGMENT_ID"="MS"."ID")
    72 - access("MS"."MARKET_SEGMENT_TYPE_ID"="MST"."ID")

    Potential issues I've seen in your statement:
    reverse(substr(reverse(ms.name),instr(reverse(ms.name),'-')+1)) cluster_name"{code}
    This is the same as:
    {code}SUBSTR(ms.name, 1, INSTR(ms.name, '-', -1) - 1){code}
    {code}select max(to_char(create_datetime,'mm/dd/yyyy')){code}
    This will ensure that 2nd December 2008 is counted as being later than 1st December 2009 - is that absolutely correct? Did you not mean this instead?:
    {code}SELECT MAX(TRUNC(create_datetime)){code}
    {code}
    AND    dad.device_id = dev.id(+)
    AND    dev.status_id = ds.id(+)
    AND    dev.model_id = hm.id(+)
    AND    dev.id = dp.paired_from_id(+)
    AND    dp.paired_to_id = dev1.id(+)
    {code}
    Those outer joins are useless! When you say "outer join tableB to tableA on the join cols and then filter the rows where tableB.some_col = some_value", what you're really saying is "inner join tableB to tableA on the join cols and tableB.some_col = some_value".
    If you're wanting to do full outer joins use ANSI join syntax *or* do the outer joins first in a sub-query and then join that to the rest of the tables.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need help th tuning query or re write the query--

    Hi,
    Need help to tune the below query or rewrite th query for reducing the execution time Please find the query and explain plan.
    QUERY
    explain plan FOR SELECT consumer_key,product_key,days_in_product,20100201 period_key FROM
    (SELECT consumer_key,
      product_key,
      days_in_product,
      row_number() over ( Partition BY consumer_key order by Days_in_product DESC) row_num
    FROM
      (SELECT consumer_key,
        product_key,
        SUM(no_ofdays) days_in_product
      FROM
        (SELECT pcv.consumer_key,
          pcv.product_key,
          pcv.product_consumer_valid_from,
          pcv.product_consumer_valid_to,
          DECODE (SIGN(20100201000000-product_consumer_valid_from),1,20100201000000,product_consumer_valid_from) period_start,
          DECODE (SIGN(20100228235959-product_consumer_valid_to),1,product_consumer_valid_to,20100228235959) period_end,
          CASE
            WHEN to_number(TO_CHAR(cd.activation_date,'YYYYMMDDHH24MISS')) BETWEEN 20100201000000 AND 20100228235959
            AND activation_date > to_Date(product_consumer_valid_to,'YYYYMMDDHH24MISS')
            THEN 0
            WHEN to_number(TO_CHAR(cd.activation_date,'YYYYMMDDHH24MISS')) BETWEEN 20100201000000 AND 20100228235959
            AND activation_date BETWEEN to_Date(product_consumer_valid_from,'YYYYMMDDHH24MISS') AND to_Date(product_consumer_valid_to,'YYYYMMDDHH24MISS')
            THEN
              --to_char(activation_date,'MON-YYYY')='PERIOD_ACTIVE'  and activation_date >= to_Date(product_consumer_valid_from,'YYYYMMDDHH24MISS') then
              (to_date(DECODE (SIGN(20100228235959-product_consumer_valid_to),1,product_consumer_valid_to,20100228235959),'YYYYMMDDHH24MISS') - to_date(TO_CHAR(activation_date,'YYYYMMDDHH24MISS'),'YYYYMMDDHH24MISS') )
            WHEN to_number(TO_CHAR(cd.activation_date,'YYYYMMDDHH24MISS')) < 20100201000000
            THEN (to_date(DECODE (SIGN(20100228235959-product_consumer_valid_to),1,product_consumer_valid_to,20100228235959),'YYYYMMDDHH24MISS') - to_Date(DECODE (SIGN(20100201000000-product_consumer_valid_from),1,20100201000000,product_consumer_valid_from),'YYYYMMDDHH24MISS') )
            WHEN to_number(TO_CHAR(cd.activation_date,'YYYYMMDDHH24MISS')) > 20100228235959
            THEN 0
            ELSE
              --unusual situation
              (to_date(DECODE (SIGN(20100228235959-product_consumer_valid_to),1,product_consumer_valid_to,20100228235959),'YYYYMMDDHH24MISS') - to_Date(DECODE (SIGN(20100201000000-product_consumer_valid_from),1,20100201000000,product_consumer_valid_from),'YYYYMMDDHH24MISS') )
          END No_ofDays
        FROM cimtran.product_consumer_validity pcv,
          consumer_dimension cd
        WHERE pcv.consumer_key           =cd.consumer_key
        AND product_consumer_valid_to   >= 20100201000000
        AND product_consumer_valid_from <= 20100228235959
          --and product_consumer_valid_from > '20090801000000'
        ORDER BY consumer_key,
          product_key,
          product_consumer_valid_from
        ) a
      GROUP BY consumer_key,
        product_key
      ORDER BY consumer_key,
        product_key
    ) WHERE row_num=1 ;EXPLAIN PLAN
    "PLAN_TABLE_OUTPUT"
    "Plan hash value: 3823907703"
    "| Id  | Operation                | Name                      | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |"
    "|   0 | SELECT STATEMENT         |                           |  4665K|   231M|       |   133K  (1)| 00:31:08 |"
    "|*  1 |  VIEW                    |                           |  4665K|   231M|       |   133K  (1)| 00:31:08 |"
    "|*  2 |   WINDOW SORT PUSHED RANK|                           |  4665K|   173M|   232M|   133K  (1)| 00:31:08 |"
    "|   3 |    VIEW                  |                           |  4665K|   173M|       |   104K  (1)| 00:24:18 |"
    "|   4 |     SORT GROUP BY        |                           |  4665K|   182M|   729M|   104K  (1)| 00:24:18 |"
    "|*  5 |      HASH JOIN           |                           |    13M|   533M|    65M| 44241   (1)| 00:10:20 |"
    "|   6 |       TABLE ACCESS FULL  | CONSUMER_DIMENSION        |  2657K|    35M|       |  4337   (1)| 00:01:01 |"
    "|*  7 |       TABLE ACCESS FULL  | PRODUCT_CONSUMER_VALIDITY |    13M|   351M|       | 15340   (2)| 00:03:35 |"
    "Predicate Information (identified by operation id):"
    "   1 - filter(""ROW_NUM""=1)"
    "   2 - filter(ROW_NUMBER() OVER ( PARTITION BY ""CONSUMER_KEY"" ORDER BY "
    "              INTERNAL_FUNCTION(""DAYS_IN_PRODUCT"") DESC )<=1)"
    "   5 - access(""PCV"".""CONSUMER_KEY""=""CD"".""CONSUMER_KEY"")"
    "   7 - filter(""PRODUCT_CONSUMER_VALID_FROM""<=20100228235959 AND "
    "              ""PRODUCT_CONSUMER_VALID_TO"">=20100201000000)"

    I doubt that this query can be tuned without using indexes. There is a lot of unnecessary work specified in your query, like unnecessary intermediate sorting and selecting unused columns. The cost based optimizer recognized it and skips some of that unnecessary work, it seems. For clarity's sake, I would rewrite your query like below. Note that the query is untested:
    select consumer_key
         , max(product_key) keep (dense_rank last order by days_in_product) product_key
         , max(days_in_product) days_in_product
         , 20100201 period_key
      from ( select pcv.consumer_key
                  , pcv.product_key
                  , sum
                    ( case
                      when to_number(to_char(cd.activation_date,'yyyymmddhh24miss')) between 20100201000000 and 20100228235959
                      then
                        case
                        when cd.activation_date > to_date(pcv.product_consumer_valid_to,'yyyymmddhh24miss')
                        then
                          0
                        when cd.activation_date between to_date(pcv.product_consumer_valid_from,'yyyymmddhh24miss') and to_date(product_consumer_valid_to,'yyyymmddhh24miss')
                        then
                          to_date(to_char(pcv.product_consumer_valid_to),'yyyymmddhh24miss'))
                          - to_date(to_char(activation_date,'yyyymmddhh24miss'),'yyyymmddhh24miss')
                        end
                      when to_number(to_char(cd.activation_date,'yyyymmddhh24miss')) < 20100201000000
                      then
                        to_date(to_char(pcv.product_consumer_valid_to),'yyyymmddhh24miss'))
                        - to_date(to_char(pcv.product_consumer_valid_from),'yyyymmddhh24miss'))
                      when to_number(to_char(cd.activation_date,'yyyymmddhh24miss')) > 20100228235959
                      then
                        0
                      end
                    ) days_in_product
               from cimtran.product_consumer_validity pcv
                  , consumer_dimension cd
              where pcv.consumer_key             = cd.consumer_key
                and product_consumer_valid_to   >= 20100201000000
                and product_consumer_valid_from <= 20100228235959
              group by consumer_key
                  , product_key
    group by consumer_keyRegards,
    Rob.

  • Help in Joining query

    Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
    create table #one (code_p char(4), code_h char(2), code_date datetime)
    insert into #one values ('DEHG','2','2010-01-01')
    insert into #one values ('DEHG','2','2011-01-01')
    insert into #one values ('DEHC','2','2009-01-01')
    insert into #one values ('DEHG','2','2012-01-01')
    create table #two (code_p char(4), code_h char(2), code_date datetime)
    insert into #two values ('DEHG','2','2010-01-01')
    insert into #two values ('DEHC','2','2009-01-01')
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
    --Result from the above query
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     2010-01-01
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     2009-01-01
    --Desired result
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     -
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     -

    Try this:
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
    from #one p
    left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • Help with my query

    Hello all,
    Total newbie to this pl/sql stuff. So, deseperately need help in my query.
    BOOKING_ID     BOOKING_STATUS     BOOKING_DATE     BOOKING_TIME     BOOKING_DATE_TIME
    1234567     CANCELLED     20090301     37252     5/1/2010 10:20
    1234567     CANCELLED 20090301     44229     5/1/2010 12:17
    1234567     BOOKED     20090301     39462     5/1/2010 10:57
    1234567     CANCELLED     20090301     43549     5/1/2010 12:05
    9671111     BOOKED     20090301     68124     5/1/2010 12:57
    9671111     CANCELLED     20090301     45001     5/1/2010 12:05
    How do I write my query such that I would get the following results:
    BOOKING_ID     BOOKING_STATUS     BOOKING_DATE     BOOKING_TIME     BOOKING_DATE_TIME
    9671111     BOOKED     20090301     68124     2/4/2010 12:17
    Basically, I am looking at the latest BOOKING_TIME and making sure the BOOKING_STATUS=BOOKED, if not, don't even bother bring back the result. Hence, you see that BOOKING_ID=1234567 is not required since at the latest BOOKING_TIME=44229, the BOOKING_STATUS=CANCELLED.
    Any help is greatly appreciated.
    Thank you in advance for your help.
    Stanley Ho

    Hi, Stanley,
    Welcome to the forum!
    Whenever you have a question, please post your sample data in a form that people can actually use. CREATE TABLE and INSERT statements are perfect.
    For example:
    CREATE TABLE     booking
    (     booking_id          NUMBER (8)
    ,     booking_status          VARCHAR2 (10)
    ,     booking_date_time     DATE
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (1234567,        'CANCELLED',        TO_DATE ('5/1/2010 10:20', 'MM/DD/YYYY HH24:MI'));
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (1234567,        'CANCELLED',        TO_DATE ('5/1/2010 12:17', 'MM/DD/YYYY HH24:MI'));
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (1234567,        'BOOKED',        TO_DATE ('5/1/2010 10:57', 'MM/DD/YYYY HH24:MI'));
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (1234567,        'CANCELLED',        TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (9671111,        'BOOKED',        TO_DATE ('5/1/2010 12:57', 'MM/DD/YYYY HH24:MI'));
    INSERT INTO  booking (booking_id, booking_status, booking_date_time)
                  VALUES (9671111,        'CANCELLED',        TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));What you want is called a Top-N Query .
    Here's one way to do it:
    WITH     got_rnum  AS
         SELECT     booking.*
         ,     ROW_NUMBER () OVER ( PARTITION BY  booking_id
                                   ORDER BY          booking_date_time     DESC
                           ) AS rnum
         FROM    booking
    SELECT     booking_id
    ,     booking_status
    ,     TO_CHAR (booking_date_time, 'YYYYMMDD')               AS booking_date
    ,     TO_CHAR (booking_date_time, 'SSSSS')               AS booking_time
    ,     TO_CHAR (booking_date_time, 'MM/DD/YYYY HH24:MI')     AS booking_date_time
    FROM     got_rnum
    WHERE     rnum          = 1
    AND     booking_status     = 'BOOKED'
    ;Notice that you don't need PL/SQL to do this; plain old SQL is good enough.
    Of course, if you're using PL/SQL for other reasons, you can use a query like this within PL/SQL.
    Dates (including time of day) should always be stored in DATE columns.
    If you have a DATE column, like booking_date_time, then there's no need for redundant date and time columns.
    You can always display just the year-month-day, or just the time, in any format, as I did above.
    The output from the query above, with the data above, is:
    BOOKING_ID BOOKING_ST BOOKING_ BOOKI BOOKING_DATE_TIM
       9671111 BOOKED     20100501 46620 05/01/2010 12:57I realize the booking_date and booking_time columns aren't quite what you posted. If they are not derivable from booking_date_time, then you probably do need separate columns for them, and those columns can easily be added to the query above.
    Edited by: Frank Kulash on Feb 5, 2010 4:41 PM
    KEEP (DENSE_RANK ...) , like Max used below, is a great tool to have in your kit. The problem with it is that you have to repeat a lot of stuff for every column, so the more columns you have in your output, the more tedious it gets. ROW_NUMBER sclaes much better, and is adaptable to more situations. I suggest you master ROW_NUMBER first, and look into KEEP (DENSE_RANK ...) later.

  • Please help with tricky query

    I need help with SQL query (if it can be accomplished with query at all).
    I'm going to create a table with structure similar to:
    Article_Name varchar2(30), Author_Name varchar2(30), Position varchar2(2). Position field is basicly position of an article author in the author list, e.g. if there is one author, his/her position is 0, if 2, then 1st author is 0, second is 1, etc.
    Article_Name Author_Name Position
    Outer Space Smith 0
    Outer Space Blake 1
    How can I automate creation of Position, based on number of authors on the fly? Let's say I have original table without Position, but I want to create a new table that will have this information.
    Regards

    If you have an existing table whose structure doesn't tell you what position the author is in, what's the algorithm you'd use to determine who was the first author, the second author, etc? If you issue a select query on a table without providing an "order by" clause, Oracle makes no guarantees about the order in which it retrieves rows.
    As an aside, why would you store position number in a varchar2 field? If it's a number, it ought to be stored as a number.
    Justin

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Need Help on Sql Query

    Hi,
    I have a client requirement to show a report on the device availability. The report should show the output as
    Node Availability%
    Formula for Availability = (Total No. of Failed/Total No. rows) * 100
    My Oracle Table has the following data
    NODE     SUMMARY
    172.16.10.55     Default Interface Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Interface Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Chassis Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Interface Ping restore for 172.16.10.55
    172.16.10.55     Default Interface Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Interface Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Chassis Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Interface Ping fail for 172.16.10.56: ICMP timeout
    In the above table the Summary column has the details like 'Ping fail' , 'Ping restore' for each Node. So, for each Node I have to compute the Total Ping Fail / (Total Ping Fail + Ping Restore) * 100 to compute the availability %.
    My output should be like the below
    Node Availability%
    172.16.10.55 55.55
    172.16.10.56 54
    Can someone please help me with query.
    I appreciate your help in advance.
    Thanks.
    Regards,
    RaviShankar.

    My Oracle Table has the following dataThat's great, but if you want maximum response to your question, then post CREATE TABLE + INSERT INTO statements.
    I currently do not have the time to turn your data into them.
    And always post the database version you're using.
    http://tkyte.blogspot.com/2005/06/how-to-ask-questions.html
    Also use the {noformat}{noformat} tag in order to post examples that benefit from staying formatted and thus readable when posted on the forum.
    Simply put the tag before and after your examples.
    For example, when you type:
    {noformat}select *
    from dual;{noformat}
    it will appear as:select *
    from dual;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need helping in writing query for finding percentage of duration

    Can any one please help in writing query for this.
    The table is like this :-
    ID     Region     Month     Duration
    I1 R1     Jan     80
    I2     R2     Jan     70
    I3     R1     Jan     70
    I4     R3     Jan     40
    I5     R1     Feb     80
    I6     R2     Feb     30
    I7     R3     Mar     100
    I want to write a query to find
    % of duration for each and every region against each and every month.
    Please help in solving this query. I am in urgent need of this.
    Thanks in advance.

    I also have to do in MS Access 2003You also have to ask into an other forum since here it's an Oracle forum, to try to find Oracle solution.
    Nicolas.

  • Can we Definine Input Help in a Query

    Hi
    Is it possible to define input help or search help in a query the same way as it is done in R3?? I will like to load specific value from a psa.
    Regards

    Hi Jacques,
    Providing Customized Input help in query directly is not possible. Instead we can provide Input help in WAD layouts for a query with the help of another Query.
    This can be made available for the users to choose with using controls such as Drop Down, Check boxes, Buttons and so on..
    Hope this helps.
    Regards.
    Shafi.

  • Help wit the query

    I need help with the query
    Here is what I need
    For a particular comm record if there is no Salary record where comm:Date = Salary:Date, then
    • Find maximum dated Salary record as of comm:Date.
    • Clone this record and set Salary:Date = comm:Date
    • Set Salary:rate = comm:rate
    Like wise for a particular Salary record If there is no comm record where Salary:Date = comm:Date then
    • Find maximum effective dated comm record as of Salary:Date
    • Apply Rate 2 amount from this maximum effective dated record to Salary record i.e. Set Salary:rate = comm:rate
    Example
    Salary Table :
    ID Sal_Date Rate Hours
    1 07/01/2011 400.00 40
    2 02/15/2011 200.00 40
    3 01/01/2011 160.00 40
    Sal_comm Table:
    Sal_Date comm_Rate
    1 07/01/2011 10.00
    4 03/01/2011 7.50
    3 01/01/2011 4.00
    I need to merge comm_Rate column in Salary table, since there is no salary record as off 03/01/2011, I need to find the maximum dated salary record as of 03/01/2011
    i.e. the record dated 02/15/2011. Now I need to clone that salary record, set the SAL_date as 03/01/2011 and update Rate2 amount. So the record set will be like:
    Sal_Date:
    id sal_Date Rate Hours comm_Rate
    1 07/01/2011 400.00 40 10.00
    4 03/01/2011 200.00 40 7.50
    2 02/15/2011 200.00 40 4.00
    3 01/01/2011 160.00 40 4.00

    So you need all used dates as the "driving" dataset. And you need the according data for each of these.
    WITH salary_table as
    (select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,400 rate,40 hours from dual union all
    select 2 id,to_date('02/15/2011','MM/DD/YYYY')sal_date,200 rate,40 hours from dual union all
    select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,160 rate,40 hours from dual),
    sal_comm as
    (select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,10 comm_Rate from dual union all
    select 4 id,to_date('03/01/2011','MM/DD/YYYY')sal_date,7.5 comm_Rate from dual union all
    select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,4 comm_Rate from dual)
    select to_char(all_dates.sal_date,'MM/DD/YYYY') sal_date,sal.rate,sal.hours,com.comm_rate
    from (select sal_date from salary_table
          union
          select sal_date from sal_comm) all_dates
    inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
               from salary_table s1) sal
      on (all_dates.sal_date between sal.sal_date and sal.next_sal_date)
    inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
               from sal_comm s1) com
      on (all_dates.sal_date between com.sal_date and com.next_sal_date)
    order by   all_dates.sal_date desc;
    SAL_DATE   RATE                   HOURS                  COMM_RATE             
    07/01/2011 400                    40                     10                    
    03/01/2011 200                    40                     7.5                   
    02/15/2011 200                    40                     4                     
    01/01/2011 160                    40                     4                     
         

  • Need urgent help with the query - Beginer

    Hello - I need help with a query to populate data in a table.Here is the scenario.
    Source1
    MnthID BranchCod CustID SegCode FXStatus ProfStatus Profit
    200712 B1 C1 20 Y Y 100
    Source2
    MnthID BranchCod CustID ProdCode ProdIndex
    200712 B1 C1 12 1
    200712 B1 C2 12 0
    Destination
    MnthID BranchCod SegCode ProdCode CountSegCust CountProdCust ProfitProdCust
    Condition and Calculations:
    1)Source1 customer are base customers.If Source2 has customers who is not in source1 then that customer's record should not be fetched.
    2)SegCode, FX Status, ProfStatus is one variable in destination table. [ SegCode = SegCode+ FXStatus (if FXStatus = Y)+ ProfStatus (if FXStatus = Y) ]
    3)CountSegCust = CountCustID Groupby MnthID,BranchCod,SegCode Only.
    4)CountProdCust = CountCustID Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
    5)ProfitProdCust = Sum of Profit of Customers Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
    Apologies for bad formatting.
    Thanks in advance!!

    A total guess indeed.
    It's not clear whether some aggregation can be done (summing counts of grouped data might cause some customers being counted more than once)
    insert into destination
    select mnthid,branchcod,segcode,prodcode,countsegcust,countprodcust,profitprodcust
      from (select s1.mnthid,
                   s1.branchcod,
                   s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end segcode,
                   s2.prodcode,
                   count(s1.custid) over (partition by s1.mnthid,
                                                       s1.branchcod,
                                                       s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
                                              order by null
                                         ) countsegcust,
                   count(case proindex when 1
                                       then custid
                         end
                        ) over (partition by s1.mnthid,
                                             s1.branchcod,
                                             s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
                                             s2.prodcode
                                    order by null
                               ) countprodcust,
                   sum(case proindex when 1
                                     then profit
                       end
                      ) over (partition by s1.mnthid,
                                           s1.branchcod,
                                           s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
                                           s2.prodcode
                                  order by null
                             ) profitprodcust,
                   row_number() over (partition by s1.mnthid,
                                                   s1.branchcod,
                                                   s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
                                                   s2.prodcode
                                          order by null
                                     ) the_row
              from source1 s1,source2 s2
             where s1.mnthid = s2.mnthid
               and s1.branchcod = s2.branchcod
               and s1.custid = s2.custid
    where the_row = 1Regards
    Etbin

  • Need help writing a query for following scenario

    Hi all, I need some help writing a query for the following case:
    One Table : My_Table
    Row Count: App 5000
    Columns of Interest: AA and BB
    Scenario: AA contains some names of which BB contains the corresponding ID. Some
    names are appearing more than once with different IDs. For example,
    AA BB
    Dummy 10
    Me 20
    Me 30
    Me 40
    You 70
    Me 50
    Output needed: I need to write a query that will display only all the repeating names with their corresponding IDs excluding all other records.
    I would appreciate any input. Thanks

    Is it possible to have a records with the same values for AA and BB? Are you interested in these rows or do you only care about rows with the same value of AA and different BB?
    With a slight modification of a previous posting you can only select those rows that have distinct values of BB for the same value of AA
    WITH t AS (
    SELECT 'me' aa, 10 bb FROM dual
    UNION ALL
    SELECT 'me' aa, 20 bb FROM dual
    UNION ALL
    SELECT 'you' aa, 30 bb FROM dual
    UNION ALL
    SELECT 'you' aa, 30 bb FROM dual
    SELECT DISTINCT aa, bb
      FROM (SELECT aa, bb, COUNT(DISTINCT bb) OVER(PARTITION BY aa) cnt FROM t)
    WHERE cnt > 1;

  • Can anyone help me with Query ?

    Hi Experts,
    Can anyone help me with Query? the query need to retrieve below info based on set of books ID.
    Needed columns:
    1 SOB     
    2 Legal Entities      
    3 Fixed Asset Org Name     
    4 Applications/Responsibilities     
    5 Operating Units     
    6 Inventory Org     
    7 COA     
    8 Assigned Responsibilities
    Thanks

    Duplicate post -- Can you help on below Query ?
    Please post only once!

Maybe you are looking for

  • Case statement

    hi. i have a case statement query. i wonder if in the select statement, can i do computation using different parameter from the main report to subreport? for example, (qty * parameter) if parameter = 0, i uses $P{abc} to multiply qty if parameter > 0

  • Printing background color - NOT

    I have someone who insists on sending me meeting minutes as email with a background color for the email. I'd like to turn off the background for printing, but can't figure how to do this. If I ask the printer to print B&W I get a grey background. In

  • Updated to iOS 6 this morning and now it can't find networks.

    When I go to wi-fi, it just continually searches for networks that I know are there and accessible.  I have tried a hard reset, as well as turning wi-fi on and off and reseting network connections. Help!

  • Can I create default sequence settings?

    Hi, Is it possible to create a default setting for new sequences instead of manually having to set it up. For example I like my timelines to be fully expanded with the display set to show all frames etc. It would be great if there was a way to always

  • SPROXY - maximum number of endpoints reached

    Hi, in transaction SPROXY i have generated some server proxies. One proxy i have deleted and new generated. Now the error message is "maxmimum number of endpoints reached". The proxy can't be activated... Where i can configure or delete the endpoints