Sql query slow due to case statement on Joins

Hi
The sql query runs very slow for 30 min when the below case statement is added on the joins. Could you please let me know how to tune it. if the case statement is not there then it runs only for 1 min.
*( CASE*
WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
THEN DT_REQ_ALL.EMPMGMTCD
END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )
SELECT  DISTINCT
  D.DB2_FDW_MGMT_V.RC_PARENT,
  DT_REQ_ALL.FULL_NAME,
  DT_REQ_ALL.EMP_COMPANY_CODE,
  DT_REQ_ALL.EMP_COST_CENTER,
  PO.PO_VENDORS.VENDOR_NAME,
  PO_PO_HEADERS_ALL2.SEGMENT1,
  PO_PO_HEADERS_ALL2.CREATION_DATE,
  PO_DIST_GL_CODE_COMB.SEGMENT1,
  PO_DIST_GL_CODE_COMB.SEGMENT2,
  PO_PO_HEADERS_ALL2.CURRENCY_CODE,
  PO_INV_DIST_ALL.INVOICE_NUM,
  PO_INV_DIST_ALL.INVOICE_DATE,
  (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
  (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
  PO_LINES_LOC.LINE_NUM,
  GL.GL_SETS_OF_BOOKS.NAME,
  CASE
        WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
        THEN 1
        ELSE 0
    END ,
  PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
  TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
FROM
  DB2.DB2_FDW_MGMT_V,
   PO.PO_VENDORS,
  PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
  GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
  AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
   PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
  PO.PO_LINES_ALL  PO_LINES_LOC,
  GL.GL_SETS_OF_BOOKS,
  PO.PO_REQUISITION_LINES_ALL,
  PO.PO_LINE_LOCATIONS_ALL,
  AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
  APPS.HR_OPERATING_UNITS,
  PO.PO_REQ_DISTRIBUTIONS_ALL,
   SELECT DISTINCT
                        PO_RDA.DISTRIBUTION_ID,
                        PO_RLA.requisition_line_id,
                        PO_RHA.DESCRIPTION PO_Descr,
                        PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                        Req_Emp.FULL_NAME,
                        GL_CC.SEGMENT1         Req_Company_Code,
                        GL_CC.SEGMENT2         Req_Cost_Center,
                        Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                        Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                        (Case
                        When GL_CC.SEGMENT2 <> 8000
                        Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                        Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                        End) EmpMgmtCD
            FROM
                        PO.po_requisition_lines_all PO_rla,
                        PO.po_requisition_headers_all PO_rha,
                        PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                        GL.GL_CODE_COMBINATIONS gl_cc,
                        HR.PER_ALL_PEOPLE_F  Req_Emp,
                        HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                        HR.hr_all_organization_units Req_Emp_Org,
                        HR.pay_cost_allocation_keyflex Req_Emp_CC
            WHERE
                        PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                        PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                        PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                        PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                        (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                        Req_Emp.effective_start_date IS NULL) AND
                        Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                        Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                        (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
        Req_Emp_Assign.effective_start_date IS NULL) AND
        Req_Emp_Assign.primary_flag = 'Y' AND
        Req_Emp_Assign.assignment_type = 'E' AND
        Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
  )  DT_REQ_ALL,
  SELECT
        FROM_CURRENCY,
        TO_CURRENCY,
        CONVERSION_DATE,
        CONVERSION_RATE
    FROM GL.GL_DAILY_RATES
    UNION
    SELECT Distinct
        'USD',
        'USD',
        CONVERSION_DATE,
        1
    FROM GL.GL_DAILY_RATES
  )  PO_Rates_GL_DR
WHERE
  ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
  AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
  AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
  AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
  AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
  AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
  AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
  AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
  AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
  AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
  AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
  AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
  AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
  AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
  AND  ( PO_INV_DIST_ALL.SOURCE(+) <> 'XML GATEWAY'   )
  AND 
   ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N') <> 'Y'   )
   AND
   ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN') <> 'FINALLY CLOSED'  )
   AND
   ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS') <> 'REJECTED'  )
   AND
   ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
   AND
   PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
     AND
   DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
   AND
  ( CASE
        WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
        THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
        WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
        THEN DT_REQ_ALL.EMPMGMTCD     
    END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )Explain plan. sorry can't get the explain plan from sql. this is from toad.
Plan
SELECT STATEMENT  ALL_ROWSCost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                               
     79 HASH UNIQUE  Cost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                          
          78 NESTED LOOPS OUTER  Cost: 53,931  Bytes: 2,607  Cardinality: 1                                                                                                                     
               75 NESTED LOOPS OUTER  Cost: 53,928  Bytes: 2,560  Cardinality: 1                                                                                                                
                    72 NESTED LOOPS  Cost: 53,902  Bytes: 2,552  Cardinality: 1                                                                                                           
                         69 NESTED LOOPS OUTER  Cost: 53,900  Bytes: 2,533  Cardinality: 1                                                                                                      
                              66 NESTED LOOPS OUTER  Cost: 53,898  Bytes: 2,521  Cardinality: 1                                                                                                 
                                   63 HASH JOIN OUTER  Cost: 53,896  Bytes: 2,509  Cardinality: 1                                                                                            
                                        40 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_DISTRIBUTIONS_ALL Cost: 3  Bytes: 26  Cardinality: 1                                                                                       
                                             39 NESTED LOOPS  Cost: 17,076  Bytes: 2,400  Cardinality: 1                                                                                  
                                                  37 NESTED LOOPS  Cost: 17,073  Bytes: 2,374  Cardinality: 1                                                                             
                                                       34 NESTED LOOPS  Cost: 17,070  Bytes: 2,362  Cardinality: 1                                                                        
                                                            31 NESTED LOOPS  Cost: 17,066  Bytes: 2,347  Cardinality: 1                                                                   
                                                                 29 NESTED LOOPS  Cost: 17,066  Bytes: 2,339  Cardinality: 1                                                              
                                                                      26 NESTED LOOPS  Cost: 17,065  Bytes: 2,312  Cardinality: 1                                                         
                                                                           23 NESTED LOOPS  Cost: 17,064  Bytes: 2,287  Cardinality: 1                                                    
                                                                                20 NESTED LOOPS  Cost: 17,062  Bytes: 2,261  Cardinality: 1                                               
                                                                                     17 NESTED LOOPS  Cost: 17,056  Bytes: 6,678  Cardinality: 3                                          
                                                                                          15 HASH JOIN  Cost: 17,056  Bytes: 6,663  Cardinality: 3                                     
                                                                                               13 MERGE JOIN CARTESIAN  Cost: 135  Bytes: 30,352  Cardinality: 14                                
                                                                                                    5 VIEW VIEW DB2.DB2_FDW_MGMT_V Cost: 4  Bytes: 2,128  Cardinality: 1                           
                                                                                                         4 SORT UNIQUE  Cost: 4  Cardinality: 1                      
                                                                                                              3 UNION-ALL                 
                                                                                                                   1 REMOTE REMOTE SERIAL_FROM_REMOTE PRDFDW.WORLD          
                                                                                                                   2 FAST DUAL  Cost: 3  Cardinality: 1            
                                                                                                    12 BUFFER SORT  Cost: 135  Bytes: 560  Cardinality: 14                           
                                                                                                         11 VIEW DB2. Cost: 131  Bytes: 560  Cardinality: 14                      
                                                                                                              10 SORT UNIQUE  Cost: 131  Bytes: 310  Cardinality: 14                 
                                                                                                                   9 UNION-ALL            
                                                                                                                        7 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_DAILY_RATES Cost: 65  Bytes: 270  Cardinality: 9       
                                                                                                                             6 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Cardinality: 1 
                                                                                                                        8 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Bytes: 4,368  Cardinality: 546       
                                                                                               14 TABLE ACCESS FULL TABLE PO.PO_HEADERS_ALL Cost: 16,920  Bytes: 32,754  Cardinality: 618                                
                                                                                          16 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Bytes: 5  Cardinality: 1                                     
                                                                                     19 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 35  Cardinality: 1                                          
                                                                                          18 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 2                                     
                                                                                22 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 26  Cardinality: 1                                               
                                                                                     21 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 1                                          
                                                                           25 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_SETS_OF_BOOKS Cost: 1  Bytes: 25  Cardinality: 1                                                    
                                                                                24 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_SETS_OF_BOOKS_U2 Cost: 0  Cardinality: 1                                               
                                                                      28 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_VENDORS Cost: 1  Bytes: 27  Cardinality: 1                                                         
                                                                           27 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_VENDORS_U1 Cost: 0  Cardinality: 1                                                    
                                                                 30 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ALL_ORGANIZATION_UNTS_TL_PK Cost: 0  Bytes: 8  Cardinality: 1                                                              
                                                            33 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINES_ALL Cost: 4  Bytes: 60  Cardinality: 4                                                                   
                                                                 32 INDEX RANGE SCAN INDEX (UNIQUE) PO.PO_LINES_U2 Cost: 2  Cardinality: 4                                                              
                                                       36 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINE_LOCATIONS_ALL Cost: 3  Bytes: 12  Cardinality: 1                                                                        
                                                            35 INDEX RANGE SCAN INDEX PO.PO_LINE_LOCATIONS_N1 Cost: 2  Cardinality: 1                                                                   
                                                  38 INDEX RANGE SCAN INDEX PO.PO_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                                             
                                        62 VIEW DB2. Cost: 36,819  Bytes: 1,090  Cardinality: 10                                                                                       
                                             61 HASH UNIQUE  Cost: 36,819  Bytes: 2,580  Cardinality: 10                                                                                  
                                                  60 NESTED LOOPS  Cost: 36,818  Bytes: 2,580  Cardinality: 10                                                                             
                                                       57 NESTED LOOPS  Cost: 36,798  Bytes: 2,390  Cardinality: 10                                                                        
                                                            54 NESTED LOOPS  Cost: 36,768  Bytes: 2,220  Cardinality: 10                                                                   
                                                                 51 NESTED LOOPS  Cost: 36,758  Bytes: 1,510  Cardinality: 10                                                              
                                                                      48 NESTED LOOPS  Cost: 36,747  Bytes: 1,050  Cardinality: 10                                                         
                                                                           45 HASH JOIN  Cost: 36,737  Bytes: 960  Cardinality: 10                                                    
                                                                                43 HASH JOIN  Cost: 34,602  Bytes: 230,340  Cardinality: 3,490                                               
                                                                                     41 TABLE ACCESS FULL TABLE HR.PER_ALL_PEOPLE_F Cost: 1,284  Bytes: 1,848,420  Cardinality: 44,010                                          
                                                                                     42 TABLE ACCESS FULL TABLE PO.PO_REQUISITION_LINES_ALL Cost: 31,802  Bytes: 18,340,080  Cardinality: 764,170                                          
                                                                                44 TABLE ACCESS FULL TABLE HR.PER_ALL_ASSIGNMENTS_F Cost: 2,134  Bytes: 822,540  Cardinality: 27,418                                               
                                                                           47 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ALL_ORGANIZATION_UNITS Cost: 1  Bytes: 9  Cardinality: 1                                                    
                                                                                46 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Cardinality: 1                                               
                                                                      50 TABLE ACCESS BY INDEX ROWID TABLE HR.PAY_COST_ALLOCATION_KEYFLEX Cost: 1  Bytes: 46  Cardinality: 1                                                         
                                                                           49 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.PAY_COST_ALLOCATION_KEYFLE_PK Cost: 0  Cardinality: 1                                                    
                                                                 53 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_HEADERS_ALL Cost: 1  Bytes: 71  Cardinality: 1                                                              
                                                                      52 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_HEADERS_U1 Cost: 0  Cardinality: 1                                                         
                                                            56 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 3  Bytes: 17  Cardinality: 1                                                                   
                                                                 55 INDEX RANGE SCAN INDEX PO.PO_REQ_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                              
                                                       59 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                        
                                                            58 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                   
                                   65 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                            
                                        64 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQ_DISTRIBUTIONS_U1 Cost: 1  Cardinality: 1                                                                                       
                              68 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_LINES_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                                 
                                   67 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_LINES_U1 Cost: 1  Cardinality: 1                                                                                            
                         71 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                                                      
                              70 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                                                 
                    74 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICE_DISTRIBUTIONS_ALL Cost: 26  Bytes: 16  Cardinality: 2                                                                                                           
                         73 INDEX RANGE SCAN INDEX AP.AP_INVOICE_DISTRIBUTIONS_N7 Cost: 2  Cardinality: 37                                                                                                      
               77 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICES_ALL Cost: 3  Bytes: 47  Cardinality: 1                                                                                                                
                    76 INDEX RANGE SCAN INDEX (UNIQUE) AP.AP_INVOICES_U1 Cost: 2  Cardinality: 1                                                                                                           Thanks

Forming a new table "new_table" with 3 tables which particiapate in CASE statement logic.
with  DT_REQ_ALL  as
   SELECT DISTINCT
                        PO_RDA.DISTRIBUTION_ID,
                        PO_RLA.requisition_line_id,
                        PO_RHA.DESCRIPTION PO_Descr,
                        PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                        Req_Emp.FULL_NAME,
                        GL_CC.SEGMENT1         Req_Company_Code,
                        GL_CC.SEGMENT2         Req_Cost_Center,
                        Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                        Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                        (Case
                        When GL_CC.SEGMENT2  8000
                        Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                        Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                        End) EmpMgmtCD
            FROM
                        PO.po_requisition_lines_all PO_rla,
                        PO.po_requisition_headers_all PO_rha,
                        PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                        GL.GL_CODE_COMBINATIONS gl_cc,
                        HR.PER_ALL_PEOPLE_F  Req_Emp,
                        HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                        HR.hr_all_organization_units Req_Emp_Org,
                        HR.pay_cost_allocation_keyflex Req_Emp_CC
            WHERE
                        PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                        PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                        PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                        PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                        (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                        Req_Emp.effective_start_date IS NULL) AND
                        Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                        Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                        (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
        Req_Emp_Assign.effective_start_date IS NULL) AND
        Req_Emp_Assign.primary_flag = 'Y' AND
        Req_Emp_Assign.assignment_type = 'E' AND
        Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
SELECT  DISTINCT
  D.DB2_FDW_MGMT_V.RC_PARENT,
  DT_REQ_ALL.FULL_NAME,
  DT_REQ_ALL.EMP_COMPANY_CODE,
  DT_REQ_ALL.EMP_COST_CENTER,
  PO.PO_VENDORS.VENDOR_NAME,
  PO_PO_HEADERS_ALL2.SEGMENT1,
  PO_PO_HEADERS_ALL2.CREATION_DATE,
  PO_DIST_GL_CODE_COMB.SEGMENT1,
  PO_DIST_GL_CODE_COMB.SEGMENT2,
  PO_PO_HEADERS_ALL2.CURRENCY_CODE,
  PO_INV_DIST_ALL.INVOICE_NUM,
  PO_INV_DIST_ALL.INVOICE_DATE,
  (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
  (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
  PO_LINES_LOC.LINE_NUM,
  GL.GL_SETS_OF_BOOKS.NAME,
  CASE
        WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
        THEN 1
        ELSE 0
    END ,
  PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
  TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
FROM
  ( SELECT * FROM
      DB2.DB2_FDW_MGMT_V,
      GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
      DT_REQ_ALL
    WHERE
          DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
       AND
        CASE
           WHEN PO_DIST_GL_CODE_COMB.SEGMENT2  <>  '1000'
           THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
           WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
           THEN DT_REQ_ALL.EMPMGMTCD     
        END =DB2.DB2_FDW_MGMT_V.MH_CHILD
   )   new_table,
   PO.PO_VENDORS,
  PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
  AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
   PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
  PO.PO_LINES_ALL  PO_LINES_LOC,
  GL.GL_SETS_OF_BOOKS,
  PO.PO_REQUISITION_LINES_ALL,
  PO.PO_LINE_LOCATIONS_ALL,
  AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
  APPS.HR_OPERATING_UNITS,
  PO.PO_REQ_DISTRIBUTIONS_ALL,
  SELECT
        FROM_CURRENCY,
        TO_CURRENCY,
        CONVERSION_DATE,
        CONVERSION_RATE
    FROM GL.GL_DAILY_RATES
    UNION
    SELECT Distinct
        'USD',
        'USD',
        CONVERSION_DATE,
        1
    FROM GL.GL_DAILY_RATES
  )  PO_Rates_GL_DR
WHERE
  ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
  AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
  AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
  AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
  AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
  AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
  AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
  AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
  AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
  AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
  AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
  AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
  AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
  AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
  AND  ( PO_INV_DIST_ALL.SOURCE(+)  'XML GATEWAY'   )
  AND 
   ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N')  'Y'   )
   AND
   ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN')  'FINALLY CLOSED'  )
   AND
   ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS')  'REJECTED'  )
   AND
   ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
   AND
   PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
  

Similar Messages

  • Sql query slowness due to rank and columns with null values:

        
    Sql query slowness due to rank and columns with null values:
    I have the following table in database with around 10 millions records:
    Declaration:
    create table PropertyOwners (
    [Key] int not null primary key,
    PropertyKey int not null,    
    BoughtDate DateTime,    
    OwnerKey int null,    
    GroupKey int null   
    go
    [Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
    With the following index:
    CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]    
    [PropertyKey] ASC,   
    [BoughtDate] DESC,   
    [OwnerKey] DESC,   
    [GroupKey] DESC   
    go
    Description of the case:
    For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
    following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
    declare @ownerKey int = 40000   
    select PropertyKey, BoughtDate, OwnerKey, GroupKey   
    from (    
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,       
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]   
    from PropertyOwners   
    ) as result   
    where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
    It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
    May be the slowness is due to as OwnerKey/GroupKey in the table  can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
    view.
    Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.

    create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
    insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
    select PropertyKey, BoughtDate, OwnerKey, GroupKey,
    RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
    from PropertyOwners
    go
    declare @ownerKey int = 1
    select PropertyKey, BoughtDate, OwnerKey, GroupKey
    from #result as result
    where result.[Rank]=1
    and result.[OwnerKey]=@ownerKey
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Sql query slow in new redhat enviornment

    We just migrated to a new dev environment in Linux REDHAT5, and now the query is very slow, and I used the TOAD to run the query, it took like 700 msecond to finish, however from any server connection, the sql query takes hours to finish.
    I checked toad monitor, it said need to increase db_buffer_cache and shared pool too small.
    Also three red alert from toad is:
    1. Library Cache get hit ratio: Dynamic or unsharable sql
    2. Chained fetch ratio: PCT free too low for a table
    3. parse to execute ratio: HIgh parse to execute ratio.
    App team said it ran real quick in the old AIX system, however I ran it in old system, and monitored in the toad, it gave me all same 5 red alerts in old system, and it did provide query results a lot quicker though.
    Here is the parameters in the old system (11gr1 on AIX):
    SQL> show parameter target
    NAME TYPE VALUE
    -------------------------------- archive_lag_target integer 0
    db_flashback_retention_target integer 1440
    fast_start_io_target integer 0
    fast_start_mttr_target integer 0
    memory_max_target big integer 0
    memory_target big integer 0
    pga_aggregate_target big integer 278928K
    sga_target big integer 0
    SQL> show parameter shared
    NAME TYPE VALUE
    -------------------------------- hi_shared_memory_address integer 0
    max_shared_servers integer
    shared_memory_address integer 0
    shared_pool_reserved_size big integer 31876710
    shared_pool_size big integer 608M
    shared_server_sessions integer
    shared_servers integer 0
    SQL> show parameter db_buffer
    SQL> show parameter buffer
    NAME TYPE VALUE
    -------------------------------- buffer_pool_keep string
    buffer_pool_recycle string
    db_block_buffers integer 0
    log_buffer integer 2048000
    use_indirect_data_buffers boolean FALSE
    SQL>
    In new 11gr2 Linux REDHAT parameter:
    NAME TYPE VALUE
    ----------- archive_lag_target integer 0
    db_flashback_retention_target integer 1440
    fast_start_io_target integer 0
    fast_start_mttr_target integer 0
    memory_max_target big integer 2512M
    memory_target big integer 2512M
    parallel_servers_target integer 192
    pga_aggregate_target big integer 0
    sga_target big integer 1648M
    SQL> show parameter shared
    NAME TYPE VALUE
    ----------- hi_shared_memory_address integer 0
    max_shared_servers integer
    shared_memory_address integer 0
    shared_pool_reserved_size big integer 28M
    shared_pool_size big integer 0
    shared_server_sessions integer
    shared_servers integer 1
    SQL> show parameter buffer
    NAME TYPE VALUE
    ----------- buffer_pool_keep string
    buffer_pool_recycle string
    db_block_buffers integer 0
    log_buffer integer 18857984
    use_indirect_data_buffers boolean FALSE
    SQL>
    Please help. Thanks in advance.

    846422 wrote:
    why need ddl? we have a sql query slow.The DDL shows the physical structure of the table and physical storage characteristics. All relevant in performance tuning.
    As for the SQL query being slow. It is not.
    You have not provided any evidence that it is slow. And no, comparing performance with a totally different system is not a valid baseline for comparison. (most cars have 4 wheels, a gearbox and a steering wheel - but that does not mean you can compare different cars like a VW Beetle with a VW Porsche)
    What is slow? What are the biggest wait states for the SQL? What does the execution plan say?
    You have not defined a problem - you identified a symptom called "+query is slow+". You need to diagnose the condition by determining exactly what the SQL qeury is doing in the database. (and please, do not use TOAD and similar tools in an attempt to do this - do it properly instead)

  • SQl query to remove all dbms_output statement

    Hi
    Can u please tell me Single SQl query to remove all dbms_output statement from package and procedure
    Umesh

    >
    Can u please tell me Single SQl query to remove all
    dbms_output statement from package and procedure
    If you are comfortable with scripting languages like Perl, Python, Ruby etc., then removing lines having the dbms_output statements from your files should be a trivial matter.
    pratz

  • SQL query slow with call to function

    I have a SQL query that will return in less than a second or two with a function in-line selected in the "from" clause of the statement. As soon as I select that returned value in the SQL statement, the statement takes from anywhere from 2 to 5 minutes to return. Here is a simplified sample from the statement:
    This statement returns in a second or 2.
    select A.pk_id
    from stu_schedule A, stu_school B, stu_year C, school_year D,
    (select calc_ytd_class_abs2(Z.PK_ID,'U') ytd_unx
    from stu_schedule Z) II
    where B.pk_id = A.fk_stu_school
    and C.pk_id = B.fk_stu_year
    and D.pk_id = C.year
    and D.school_year = '2011';
    if I add this function call in, the statement runs extremely poor.
    select A.pk_id,
    II.ytd_unx
    from stu_schedule A, stu_school B, stu_year C, school_year D,
    (select calc_ytd_class_abs2(Z.PK_ID,'U') ytd_unx
    from stu_schedule Z) II
    where B.pk_id = A.fk_stu_school
    and C.pk_id = B.fk_stu_year
    and D.pk_id = C.year
    and D.school_year = '2011';
    Here is the function that is called:
    create or replace FUNCTION calc_ytd_class_abs2 (p_fk_stu_schedule in varchar2,
    p_legality in varchar2) return number IS
    l_days_absent number := 0;
    CURSOR get_class_abs IS
    select (select nvl(max(D.days_absent),'0')
    from cut_code D
    where D.pk_id = C.fk_cut_code
    and (D.legality = p_legality
    or p_legality = '%')) days_absent
    from stu_schedule_detail B, stu_class_attendance C
    where B.fk_stu_schedule = p_fk_stu_schedule
    and C.fk_stu_schedule_detail = B.pk_id;
    BEGIN
    FOR x in get_class_abs LOOP
    l_days_absent := l_days_absent + x.days_absent;
    END LOOP;
    return (l_days_absent);
    END calc_ytd_class_abs2;

    Query returns anywhere from 6000 to 32000 rows. For each of those rows a parameter is passed in to 4 different functions to get ytd totals. When I call the functions in the in-line view but do not select from them in the main SQL, the report (oh, this is Application Express 4.0 interactive reports, just an FYI) runs fast. The report comes back in a few seconds. But when I select from the in-line view to display those ytd totals, the report runs extremely slow. I know there are the articles about context switching and how mixing SQL with PL/SQL performs poorly. So I tried a pipeline table function where the function for the ytd totals populate the columns of the pipeline table and I select from the pipeline table in the SQL query in the interactive report. That seemed to perform a little worse from what I can tell.
    Thanks for any help you can offer.

  • SQL query problem - select max (case... aggregate function)

    Hi,
    I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
    select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
    select
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    Any ideas?

    Moved to more sutable forum, sorry.

  • SQL Query for real time resource stats

    Does anyone know what the query would be to duplicate the real time resource stats page in version 8 or above of UCCX?  I need to build a custom web page that displays the same information.  I've got all the connectivity to the database just fine and can query it and display information.  Just can't figure out what the SQL would be that would extract that information.

     Michael,
    you can try :
    SELECT x.resourceName, t.eventType, x.datetime FROM (SELECT t1.resourceID, t1.resourceName, MAX(t2.eventDateTime) AS datetime FROM Resource AS t1 INNER JOIN AgentStateDetail AS t2 ON t2.agentID = t1.resourceID GROUP BY t1.resourceID, t1.resourceName ) AS x INNER JOIN AgentStateDetail AS t ON t.agentID = x.resourceID AND t.eventDateTime = x.datetime ORDER BY x.resourceName
    You will need to translate the eventType into the "readable" status like Talking or Not Ready with an IF or Case statement.
    Regards,
    Jeroen

  • SEQUENCE Select within an SQL Query with an ORDER BY statement

    Does anyone know why you cannot use an ORDER BY statement within an SQL query when also selecting from a SEQUENCE? My query was selecting production data as a result of a filtered search. I want to take the results of the filtered search and create a transaction. I have a sequence for generating transaction numbers where I select NEXTVAL. Since I could possibly obtain multiple, yet distinct, rows based upon my search criteria, I wanted to use an ORDER BY statement to simplify and order the resulting row(s).
    I was able to get the SQL select with SEQUENCE.NEXTVAL to work without the ORDER BY, so I know that my SQL is correct. Thanks in-advance.

    Okay,
    I understand. You want the sequence assigned first and the you want to ORDER BY. You
    can do this using pipelined functions. See here:
    CREATE OR REPLACE TYPE emp_rec_seq AS OBJECT (
       seq     NUMBER,
       ename   VARCHAR2 (20),
       job     VARCHAR2 (20),
       sal     NUMBER
    CREATE OR REPLACE TYPE emp_tab_seq AS TABLE OF emp_rec_seq;
    CREATE OR REPLACE FUNCTION get_emp_with_sequence
       RETURN emp_tab_seq PIPELINED
    IS
       my_record   emp_rec_seq := emp_rec_seq (NULL, NULL, NULL, NULL);
    BEGIN
       FOR c IN (SELECT dummy.NEXTVAL seq, ename, job, sal
                   FROM emp)
       LOOP
          my_record.seq := c.seq;
          my_record.ename := c.ename;
          my_record.job := c.job;
          my_record.sal := c.sal;
          PIPE ROW (my_record);
       END LOOP;
       RETURN;
    END get_emp_with_sequence;after that, you can do a select like this:
    SELECT seq, ename, job, sal
      FROM TABLE (get_emp_with_sequence)
      order by enamewhich will get you this:
           SEQ ENAME                JOB                         SAL
          1053 BLAKE                MANAGER                    2850
          1054 CLARK                MANAGER                    2450
          1057 FORD                 ANALYST                    3000
          1062 JAMES                CLERK                       950
          1055 JONES                MANAGER                    2975
          1052 KING                 MANAGER                   20000
          1060 MARTIN               SALESMAN                   1250
          1063 MILLER               CLERK                      1300
          1064 DKUBICEK             MANAGER                   12000
          1056 SCOTT                ANALYST                    3000
          1058 SMITH                CLERK                       800
          1061 TURNER               SALESMAN                   1500
          1059 WARD                 SALESMAN                   1250Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://htmldb.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • MDX Query - Rolling Up A Case Statement

    Hi,
    I have the following query 
    with
    member measures.[EmployeeNumber] as [Employee].[EmployeeNumber].currentmember.member_name
    member measures.[Type] as Case When [WorkDay].[DayOfWeek].currentmember.member_name = "Sunday" Then "PenaltyRate" Else "Standard" End
    Select {
    measures.[EmployeeNumber]
    , measures.[Type]
    , measures.[ContactHours]
    } on 0,
    non empty
    [Employee].[EmployeeNumber].[all].children*
    [WorkDay].[DayOfWeek].[all].children
    Having measures.[ContactHours] <> 0
    on 1
    From MyCube
    and I want write a MDX query that takes this result set and sums that ContactHours per EmployeeNumber and per Type i.e. excluding the WorkDay.DayOfWeek hierarchy from the results.
    This would be the same as doing 
    Select Sum(ContactHours), EmployeeNumber, Type
    From ResultsSet
    Group By EmployeeNumber, Type
    in SQL.

    Hi Joerne,
    According to your description, you want to get a MDX query which equivalent of a GROUP BY in T-SQL, right? In this case, please refer to the link below to see the article which give out some sample query in MDX that equivalent of a filtered GROUP BY in T-SQL.
    MDX equivalent of a filtered GROUP BY in SQL
    Hope this helps.
    Regards,
    Charlie Liao
    TechNet Community Support

  • Sql query slow while using poc *C, OCI

    Sql query is taking long time while using fetching records from RAC using Pro *C, OCI. Same query working fine while using JDBC connection.what could be the issue.Please help
    Thanks,
    Sam

    Pro*C is not part of Oracle Solaris Studio (formerly Sun Studio). Studio has no special support for database programming. You are more likely to get a helpful answer in a database programming forum. Start here:
    https://forums.oracle.com/forums/category.jspa?categoryID=18

  • What is the best way to Optimize a SQL query : call a function or do a join?

    Hi, I want to know what is the best way to optimize a SQL query, call a function inside the SELECT statement or do a simple join?

    Hi,
    If you're even considering a join, then it will probably be faster.  As Justin said, it depends on lots of factors.
    A user-defined function is only necessary when you can't figure out how to do something in pure SQL, using joins and built-in functions.
    You might choose to have a user-defined function even though you could get the same result with a join.  That is, you realize that the function is slow, but you believe that the convenience of using a function is more important than better performance in that particular case.

  • Is it possible to use a case statement when joining different tables based on input parameters?

    Hi,
    I have a scenario where my stored procedure takes 5 parameters and the users can pass NULL or some value to these parameters and based on the parameters, I need to pull data from various tables.
    Is it possible to use a case statement in the join, similar the one in the below example. I'm getting error when I use the below type of statement.
    select a.*
    from a
    case
    when parameter1=1 then
    inner join a on a.id = b.id
    when parameter1=2 then
    inner join a on a.id = c.id
    end;
    Please let me know, if this type of statement works, and if it works will it create any performance issues?. If the above doesn't work, could you please give me some alternate solutions?
    Thanks.

    Here's a technique for joining A to B or C depending on the input parameters. In theory, you are joining to both tables but the execution plan includes filters to skip whichever join is not appropriate. The drawback is that you have to do outer joins, not inner ones.
    CREATE TABLE A AS SELECT LEVEL ak FROM dual CONNECT BY LEVEL <= 100;
    CREATE TABLE b AS SELECT ak, bk
    FROM A, (SELECT LEVEL bk FROM dual CONNECT BY LEVEL <= 10);
    CREATE TABLE c(ak, ck) AS SELECT ak, bk*10 FROM b;
    variable p1 NUMBER;
    variable p2 NUMBER;
    exec :p1 := 1;
    exec :p2 := 20;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.01 |       7 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |
    |*  5 |     FILTER            |                 |      1 |        |      9 |00:00:00.01 |       4 |
    |*  6 |      TABLE ACCESS FULL| B               |      1 |      9 |      9 |00:00:00.01 |       4 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |
    |*  8 |    FILTER             |                 |      1 |        |      0 |00:00:00.01 |       0 |
    |*  9 |     TABLE ACCESS FULL | C               |      0 |      9 |      0 |00:00:00.01 |       0 |
    Predicate Information (identified by operation id):
       1 - access("A"."AK"="ITEM_0")
       2 - access("A"."AK"="ITEM_1")
       3 - filter("A"."AK"<=9)
      5 - filter(:P1 IS NOT NULL)
       6 - filter(("B"."AK"<=9 AND "B"."BK"=:P1))
       8 - filter((:P2 IS NOT NULL AND :P1 IS NULL))
       9 - filter(("C"."AK"<=9 AND "C"."CK"=:P2))
    You can see that table C was not really accessed: the buffer count is 0.
    exec :p1 := NULL;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    Now table B is not accessed.
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.02 |       7 |      2 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.02 |       7 |      2 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |*  5 |     FILTER            |                 |      1 |        |      0 |00:00:00.01 |       0 |      0 |
    |*  6 |      TABLE ACCESS FULL| B               |      0 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |
    |*  8 |    FILTER             |                 |      1 |        |      9 |00:00:00.01 |       4 |      2 |
    |*  9 |     TABLE ACCESS FULL | C               |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |

  • Pl/sql function body returning SQL query - if with in select statement

    hello all,
    I have a condition where when summary field is checked alone we have show that column for the users in the report. Is IF statement possible for this case ? I have given the code below.. is it possible to write something like below or is there any other way to do it ?
    v_sql := 'select TBLCASES.INVESTIGATOR as INVESTIGATOR,';
    v_sql := v_sql ||' TBLCASES.CASENUMBER as CASENUMBER,';
    v_sql := v_sql ||' TBLCASES.OPENDATE as OPENDATE,';
    v_sql := v_sql ||' TBLCASES.ESTCOMPLETE as TARGETDATE,';
    v_sql := v_sql ||' TBLCASES.STATUS as STATUS,';
    v_sql := v_sql ||' TBLCASES.CASECODE as CASECODE,';
    v_sql := V_sql ||' TBLCASES.FAIR_HOTLINE as FAIRHotline,';
    v_sql := v_sql ||' TBLCASES.NYSIG as NYSIGCase,';
    v_sql := v_sql ||' TBLCASES.REGION as Region,';
    IF :P44_INCLUDE_SUMMARY_FIELD is not null THEN
    v_sql := v_sql||' TBLCASES.SUMMARY as SUMMARY,';
    END IF ;
    v_sql := v_sql ||' TBLCASES.PROGAREA as PROGArea ';
    v_sql := v_sql ||' from TBLCASES where 1=1';
    ..\

    Hi Lucy,
    You are adding and removing a column from a report so it may help to have the extra on the end of the query.
    Do you get an error? If so paste it in...
    BUT - this I would put a condition on the column where ':P44_INCLUDE_SUMMARY_FIELD is not null '
    Under he report's "Column Attributes" Select the column edit icon and it has a "Condition" breadcrumb.
    Select "Value of Item in Expression 1 is Not Null" and put P44_INCLUDE_SUMMARY_FIELD in Expression 1 text area.
    And I make it more readable like this when I do dynamic SQL:
    IF :P44_INCLUDE_SUMMARY_FIELD is not null THEN
    v_INCLUDE_SUMMARY_FIELD := ' TBLCASES.SUMMARY as SUMMARY ';
    END IF ;
    v_sql := 'select TBLCASES.INVESTIGATOR as INVESTIGATOR,
    TBLCASES.CASENUMBER as CASENUMBER,
    TBLCASES.OPENDATE as OPENDATE,
    TBLCASES.ESTCOMPLETE as TARGETDATE,
    TBLCASES.STATUS as STATUS,
    TBLCASES.CASECODE as CASECODE,
    TBLCASES.FAIR_HOTLINE as FAIRHotline,
    TBLCASES.NYSIG as NYSIGCase,
    TBLCASES.REGION as Region,
    TBLCASES.PROGAREA as PROGArea,'||
    v_INCLUDE_SUMMARY_FIELD ||
    'from TBLCASES where 1=1; ';
    Hope it helps,
    BC

  • Query slow due to dblink

    Hi All,
    We are experiencing slow performance for a query which is using dblink.
    Our Database version is 8i
    Our OS is Windows 2000
    the explain plan is as below.
    Explain plan:-
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=7494 Card=1 Bytes=38
    0)
    1 0 SORT (ORDER BY) (Cost=7494 Card=1 Bytes=380)
    2 1 SORT (GROUP BY) (Cost=7494 Card=1 Bytes=380)
    3 2 HASH JOIN (Cost=7489 Card=1 Bytes=380)
    4 3 MERGE JOIN (CARTESIAN) (Cost=9 Card=17 Bytes=1479)
    5 4 NESTED LOOPS (Cost=8 Card=1 Bytes=63)
    6 5 TABLE ACCESS (FULL) OF 'CATMAP' (Cost=1 Card=1 B
    ytes=14)
    7 5 TABLE ACCESS (BY GLOBAL INDEX ROWID) OF 'DOCPART
    EXT' (Cost=7 Card=1 Bytes=49)
    8 7 INDEX (RANGE SCAN) OF 'DOCPARTEXT_I10' (NON-UN
    IQUE) (Cost=3 Card=1)
    9 4 SORT (JOIN) (Cost=2 Card=17 Bytes=408)
    10 9 TABLE ACCESS (FULL) OF 'PARTGROUP' (Cost=1 Card=
    17 Bytes=408)
    11 3 REMOTE* (Cost=7311 Card=1161896 Bytes=340435528) PRICE
    11 SERIAL_FROM_REMOTE SELECT "PARTID","PARTGROUP","PARTDESCRIPTION
    ","IMAGEFILENAME" FROM "DIST"."
    Statistics
    18 recursive calls
    14 db block gets
    38130 consistent gets
    378 physical reads
    172 redo size
    65623 bytes sent via SQL*Net to client
    2983 bytes received via SQL*Net from client
    25 SQL*Net roundtrips to/from client
    3 sorts (memory)
    0 sorts (disk)
    360 rows processed
    The above query sometimes execute in 2 seconds and sometimes it takes almost 150 secs
    Please advice how to tune this query.
    Regards,
    ang

    Hi Anurag,
    I found below stuff in system wait events.
    EVENTS Total Waits
    SQL*Net message to client     112838591     0     0     0
    SQL*Net message to dblink     297216585     0     0     0
    SQL*Net more data to client     7965780     0     0     0
    SQL*Net more data to dblink     2207     0     0     0
    SQL*Net message from client     112838213     0     0     0
    SQL*Net more data from client     525083     0     0     0
    SQL*Net message from dblink     297216585     0     0     0
    SQL*Net more data from dblink     94103530     0     0     0
    SQL*Net break/reset to client     10115895     0     0     0
    SQL*Net break/reset to dblink     41218     0     0     0
    Above are the highest wait events in v$system_event.
    Regards,
    Ang

  • MS SQL query slow using view column as criteria

    HI,
    I am experiencing a very frustrate problem. I have 2 tables, and create a view
    to union these 2 tables, when do a select on this view using the column of the
    view as criteria is took more 1 minutes, but the query runs fine in Qurey Analyzer.
    Anybody has the same experience? is this the problem with jdbc?

    I searched http://e-docs.bea.com/wls/docs70/index.html, also searched the documentation
    for wls6.1, wls5.1. As you pointed I searched support site, they are all the customer
    case, it's not formal documentation.
    Joe Weinstein <[email protected]> wrote:
    >
    >
    jen wrote:
    Thanks. but I search on the table is fine (the same column). is thereany db setting
    could be tuned? so the view is the problem? No, it's a client decision/issue. If you defined your tables to have
    nvarchar columns
    the jdbc driver's parameter values would be fine as-is.
    I searched "useVarChars" on whole
    site and can't find anything.Which site? This is a property of the weblogic.jdbc.mssqlserver4.Driver.
    I just went to www.bea.com/support and entered useVarChars in the Ask
    BEA
    question panel and got hits...
    Joe
    Joe Weinstein <[email protected]> wrote:
    Jen wrote:
    Sorry it's my bad. I am testing on wls81, but the problems is on wls70,so they
    are using different drivers.
    You are the magic man. It worked on wls81 now. I am sure it will curethe problem
    on wls70. Is there any documentation on this? Why it is not a problemon some
    databse server? ThanksSure. The issue has to do with the MS client-DBMS protocol having evolved
    from
    an 8-bit (7-bit really) character representation. Now it has a newer
    16-bit
    way, to transfer NVARCHAR data. Java characters are all 16-bit, so
    by default
    a JDBC driver will send Java parameters over as NVARCHAR data. This
    is
    crucial
    for Japanese data etc. However, once simple ASCII data is transformed
    to an
    NVARCHAR format, the DBMS can't directly compare it to varchar data,
    or use it
    in index searches. The DBMS has to convert the VARCHAR data to NVARCHAR,
    but it
    can't guarantee that the converted data will retain the same ordering
    as the index,
    so the DBMS has to do a table scan!
    The properties I suggested are each driver's way of allowing you
    to say "I'm
    a simple American ;) I am using simple varchar data so please sendmy
    java
    strings that way.". This allows the DBMS to use your varchar indexes
    in queries.
    Joe Weinstein at BEA
    Joe Weinstein <[email protected]> wrote:
    Jen wrote:
    It doesn't cure the problem. Here is my pool
    <JDBCConnectionPool DriverName="weblogic.jdbc.sqlserver.SQLServerDriver"Name="test_pool"
    Password="{3DES}fKSovViFe5kHzl/vTs0LVQ==" Properties="user=user;PortNumber=1543;useVarChars=true;ServerName=194.20.2.10;DatabaseName=devDB"
    Targets="admin" TestTableName="SQL SELECT COUNT(*) FROM sysobjects"URL="jdbc:bea:sqlserver://194.20.2.10:1543"/>
    Strange is some database is fine.Oh, sorry. I thought it was the older weblogic driver. Change the
    useVarChars=true to sendStringParametersAsUnicode=false
    Let me know... Also, I suggest changing the TestTableName to "SQL
    select
    1".
    For MS, that will be much more efficient than involving a full count
    of sysobjects!
    Joe
    Joe Weinstein <[email protected]> wrote:
    Jen wrote:
    You are right. Tadaa! Am I Kreskin, or what? ;) Here's what I recommend:
    In your pool definition, for this driver add a driver property:
    useVarChars=true
    and let me know if it's all better.
    Joe
    I am using weblogic jdbc driver weblogic.jdbc.mssqlserver4.Driver.
    here is the code:
    getData(Connection connection, String stmt, ArrayList arguments)
         PreparedStatement pStatement=null;>>>>>>>>     ResultSet resultSet=null;>>>>>>>>     try {>>>>>>>>         pStatement = connection.prepareStatement(stmt);>>>>>>>>         for (int i = 1; i <= arguments.size(); i++) {>>>>>>>>          pStatement.setString(i, (String) arguments.get(i-1));>>>>>>>>                    resultSet = pStatement.executeQuery(); //this statement takesmore than 1
    min.
    Joe Weinstein <[email protected]> wrote:
    Jen wrote:
    HI,
    I am experiencing a very frustrate problem. I have 2 tables,
    and
    create
    a view
    to union these 2 tables, when do a select on this view using
    the
    column
    of the
    view as criteria is took more 1 minutes, but the query runs
    fine
    in
    Qurey Analyzer.
    Anybody has the same experience? is this the problem with jdbc?
    I have suspicions... Show me the jdbc code. I'm guessing it's
    a
    PreparedStatement,
    and you send the search criterion column value as a parameter
    you
    set
    with a
    setString().... Let me know... (also let me know which jdbc driveryou're
    using).
    Joe

Maybe you are looking for

  • Probleme mit ACR Editor 8.1

    Hi, ich habe bereits im Camera Raw Forum geschrieben (im schlechten englisch,hihi). Nun schreibe ich hier auch nochmal mein Problem, vllt. kann das jemand nachvollziehen und hat das gleiche Problem. Ich habe Photoshop CS6 als CC Produkt. Dazu habe ic

  • Connection to my Wi-Fi

    Hi I am new to playbook.  My tablet see's my WI-fi    I enter the password as requested but it will not allow me to connect.  Can some one help as apparently I am not eligible for 90 day support.  don't know why.  tks Solved! Go to Solution.

  • Reg. PDF file stored in oracle server directory

    Dear All , How to stored PDF generated file in oracle server directory. Thanks & Regards shailesh

  • Hide Overview & Miscellaneous from Employee Profile in Team View

    Hi all, I want to hide everything other than Short profile in Employee Profile in Team View(MSS) How can I do it.? Thanks, Namsheed

  • Two items same colour swatch; showing differently!

    I am constantly having this problem so I thought I'd ask for a bit of guidance. I have a colour swatch that I use regularly, and I use it for table headers a lot. For some reason on the same page, using the same swatch the table headers look differen