Help needed in tuning a complex query

Hi,
I am running Oracle 9i on Solaris 9.
I have the following query that's running for more than 20 hours and not finishing. I am attaching TOAD explain plan and number of records of the tables. If somebody can give some ideas, I will really appreciate that.
Thanks.
SELECT
a.AGREMENT_number, SUBSTR (d.product_number, 11, 9),
SUBSTR (d.product_number, 1, 9), SUBSTR (d.product_name, 1, 80),
'TERMS', e.valuenumber,
NVL (SUBSTR (j.valuestring, 1, 1),
NVL ((SELECT 'P'
FROM PCPINDASSN_CLNT n
WHERE (k.state = n.state OR n.state = 'US')
AND m.value_string = n.specialty),
'S'
SUBSTR (i.valuestring, 1, 9),
GREATEST (NVL (d.date_value_2, a.effectivestartdate),
NVL (g.valuedate, a.effectivestartdate)
LEAST (NVL (d.date_value_1, NVL (a.effectiveenddate, '31-DEC-9999')),
NVL (h.valuedate, NVL (a.effectiveenddate, '31-DEC-9999'))
FROM AGREMENT a,
AGREMENTREVI b,
AGREMENTLR c,
LINEREVI d,
VLTABL e,
VLTABL f,
VLTABL g,
VLTABL h,
VLTABL i,
VLTABL j,
VEND_PHY_AGREMENT_CLNT k,
PARTICIPANT l,
CUSTPROP m
WHERE a.ID = b.AGREMENTID
AND a.REVISION = b.REVISION
AND a.ID = c.AGREMENT_id
AND a.REVISION = c.AGREMENT_REVISION
AND c.LINEREVI_ID = d.LINEREVI_ID
AND a.ID = e.AGREMENTID
AND a.REVISION = e.REVISION
AND e.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01')
AND a.ID = f.AGREMENTID
AND a.REVISION = f.REVISION
AND f.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01 Transaction Type')
AND a.ID = g.AGREMENTID
AND a.REVISION = g.REVISION
AND g.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01 Effective Date')
AND a.ID = h.AGREMENTID
AND a.REVISION = h.REVISION
AND h.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01 Cancel Date')
AND a.ID = i.AGREMENTID
AND a.REVISION = i.REVISION
AND i.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01 NWRK Number')
AND a.ID = j.AGREMENTID
AND a.REVISION = j.REVISION
AND j.CHNG_ID = (SELECT CHNG_ID
FROM CHANGING
WHERE NAME = 'Ct. MSTR 01 PCP Override')
AND REPLACE (d.product_number, ',') = l.external_system_id
AND l.PARTICIPANT_id = m.bo_key
AND m.property_pkid = (SELECT pkid
FROM CUPROP
WHERE NAME = 'prov_spclty_ind')
AND e.valuenumber IS NOT NULL
AND UPPER (NVL (f.valuestring, 'Processed')) NOT LIKE '%CANCEL%'
AND a.status IN ('Active', 'Executed')
AND LEAST (NVL (d.date_value_1, NVL (a.effectiveenddate, '31-DEC-9999')),
NVL (h.valuedate, NVL (a.effectiveenddate, '31-DEC-9999'))
) > SYSDATE
AND a.AGREMENT_NUMBER = k.VENDDOCID
AND k.delta IS NULL;
Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
SELECT STATEMENT Optimizer Mode=FIRST_ROWS          1           65641                     
TABLE ACCESS FULL     VEND.PCPINDASSN_CLNT     1      7      15                     
NESTED LOOPS          1      822      65641                     
NESTED LOOPS          1      750      65637                     
NESTED LOOPS          1      700      65634                     
NESTED LOOPS          1      690      65171                     
NESTED LOOPS          1      616      65169                     
NESTED LOOPS          1      546      65166                     
NESTED LOOPS          1      511      65164                     
NESTED LOOPS          1      434      65160                     
NESTED LOOPS          1      357      65156                     
NESTED LOOPS          1      283      65152                     
NESTED LOOPS          3      627      65140                     
NESTED LOOPS          826      109 K     61836                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     2 K     216 K     53184                     
INDEX RANGE SCAN     VEND.VLTABL_CHNG_ID_INDX     57 K          448                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.AGREMENT     1      59      3                     
INDEX UNIQUE SCAN     VEND.AGREMENT_PK     1           2                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     1      73      4                     
INDEX UNIQUE SCAN     VEND.VLTABL_PK     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     1      74      4                     
INDEX UNIQUE SCAN     VEND.VLTABL_PK     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     1      74      4                     
INDEX UNIQUE SCAN     VEND.VLTABL_PK     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     1      77      4                     
INDEX UNIQUE SCAN     VEND.VLTABL_PK     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.VLTABL     1      77      4                     
INDEX UNIQUE SCAN     VEND.VLTABL_PK     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CHANGING     1      65      2                     
INDEX UNIQUE SCAN     VEND.NAME_APK     1           1                     
TABLE ACCESS BY INDEX ROWID     VEND.AGREMENTREVI     1      35      2                     
INDEX UNIQUE SCAN     VEND.AGREMENTREVI_PK     1           1                     
INDEX RANGE SCAN     VEND.PK_AGREMENTLR     6      420      3                     
TABLE ACCESS BY INDEX ROWID     VEND.LINEREVI     1      74      2                     
INDEX UNIQUE SCAN     VEND.SYS_C004896     1           1                     
TABLE ACCESS FULL     VEND.VEND_PHY_AGREMENT_CLNT     1      10      463                     
TABLE ACCESS BY INDEX ROWID     VEND.PARTICIPANT     1      50      3                     
INDEX RANGE SCAN     VEND.PARTICIPANT_EXTERNAL_SYSTEM_ID_CUST1     1           2                     
TABLE ACCESS BY INDEX ROWID     VEND.CUSTPROP     1      72      4                     
INDEX RANGE SCAN     VEND.CUSTOMPROPVAL_KEY_PK_VAL     1           3                     
TABLE ACCESS BY INDEX ROWID     VEND.CUPROP     1      47      1                     
INDEX UNIQUE SCAN     VEND.UNIQUE_NAME     1                               
Table Name               Records
CUPROP                    21
VEND_PHY_AGREMENT_CLNT          306034
AGREMENTREVI               455167
LINEREVI               1425077
AGREMENT               1797443
PARTICIPANT               3444813
AGREMENTLR               10129747
CUSTPROP               47342607
VLTABL                    328107500
*********************************************************************************************************************

user578671 if you cannot take constructive advise and need to have it sugar coated, please do not post in a public forum.
Toad explain plans are Re: Tool for Explain Plan?? for anyone that cannot see your monitor, unformatted explain plans are also useless.
The link provided by SomeoneElse shows you what information is needed and how to post it in a way that people can read it and help you. Got it?

Similar Messages

  • Help needed in tuning a query

    Hi,
    I need some help in performing tuning of a big query. Explain plan is as under:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    Edited by: AbdulHadi on Sep 16, 2011 3:56 PM
    Edited by: AHadi on Sep 19, 2011 10:02 AM

    3     SORT GROUP BY          47916     25M     491G     15M (3)     17:30:31               
    4     VIEW          870M     445G          15M (2)     17:24:08               
    5     HASH GROUP BY          870M     427G     885G     15M (2)     17:24:08               
    In above steps its using very high temporary tablespace usage. please try to tune your query.
    - dynamic sampling used for this statement
    The statistics appears to be stale.

  • Help needed in building a  sql query

    Hello,
    I am using Oracle 10g db.
    I have 3 tables table1 and table2 and table3
    I am writing one sql query which is like
    select table1.a a1,(select distinct b from table2,table3 where table2.id=table3.id and table1.id=table2.id) b1
    from table1
    Now the b1 value may give more then 1 values so when i am trying to execute the query its giving me error.
    What i would like to have is if it gives returns more then 1 value then add that value as a new column means if b1 gives like abc and def as values.
    Then i want the sql to return like
    acolvalue abc def as a single row.
    Is this possible to do?
    Thanks

    Hello,
    The approach which i took is i wrote a function which gives me the b values , sseparated.
    Then i am building a outer query considering the max of b so i just found there are max 10 values which one row is showing.
    select b11,b12,b13,,,b10
    from (
    select table1.a a1,func(select distinct b from table2,table3 where table2.id=table3.id and table1.id=table2.id) b1
    from table1)
    but now i am facing problem like the value of b1 is a,b,c
    i want to use the substr and instr function to get
    a as b11
    b as b12
    c as b13
    can anyone pls help me out to write a query? i am getting b11 but other values are somehow not coming.
    for b11
    i used
    substr(b1,1,instr(b1,',',1,1)-1)
    Thanks

  • Help needed in tuning this query

    This is the SQL i would like to tune for performace...
    The table structure is given below.
    The table has about 2 million rows.
    From the second day onwards only around 10% of records will be between Load_Start_Time and Load_End_Time. Among these around 50% will have THAMES_URN_WITH_ROLE_SUFFIX as 'TP%'. At present there are unique and primary key indexes on THAMES_URN_WITH_ROLE_SUFFIX .
    I'm sure that we need a b-tree index on STG_UPDATE_DATE_TIME as it is the column with good selectivity.
    I'm primarily concerned about the substr, instr and reverese on THAMES_URN_WITH_ROLE_SUFFIX.
    Also pls. let me know if the order of predicates is right.
    Thanks in advance.
    SELECT TPD_STG_TL_SF_LEGAL_OWNER.THAMES_URN, TPD_STG_TL_SF_LEGAL_OWNER.UPDATE_SOURCE, TPD_STG_TL_SF_LEGAL_OWNER.SOURCE_EXTRACT_DATE_TIME, TPD_STG_TL_SF_LEGAL_OWNER.LEGAL_OWNERSHIP_ISSUE_IND, TPD_STG_TL_SF_LEGAL_OWNER.CONTACTABLE_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.ADMIN_CONTROL_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.BANKRUPTCY_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.ASSIGNED_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.IN_TRUST_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.DIVORCE_CASE_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.POA_COP_INDICATOR, TPD_STG_TL_SF_LEGAL_OWNER.CLEANSING_STATUS, TPD_STG_TL_SF_LEGAL_OWNER.CATEGORY
    FROM
    TPD_STG_TL_SF_LEGAL_OWNER
    WHERE
    ((TPD_STG_TL_SF_LEGAL_OWNER.STG_UPDATE_DATE_TIME > '$$Load_Start_Time'
    AND
    TPD_STG_TL_SF_LEGAL_OWNER.STG_UPDATE_DATE_TIME <= '$$Load_End_Time')
    OR
    (TPD_STG_TL_SF_LEGAL_OWNER.TPDB_PROCESSED_IDENTIFIER != 'Y') )
    AND
    SUBSTR(TPD_STG_TL_SF_LEGAL_OWNER.THAMES_URN_WITH_ROLE_SUFFIX,1,2)='TP'
    AND
    SUBSTR(REVERSE( TPD_STG_TL_SF_LEGAL_OWNER.THAMES_URN_WITH_ROLE_SUFFIX),INSTR(REVERSE( TPD_STG_TL_SF_LEGAL_OWNER.THAMES_URN_WITH_ROLE_SUFFIX),'-',1)-1,1)!='S'
    ========================================
    CREATE TABLE TPD_STG_TL_SF_LEGAL_OWNER
    THAMES_URN VARCHAR2(35 BYTE) NOT NULL,
    UPDATE_SOURCE VARCHAR2(3 BYTE),
    SOURCE_EXTRACT_DATE_TIME DATE,
    LEGAL_OWNERSHIP_ISSUE_IND CHAR(1 BYTE),
    CONTACTABLE_INDICATOR CHAR(1 BYTE),
    ADMIN_CONTROL_INDICATOR CHAR(1 BYTE),
    BANKRUPTCY_INDICATOR CHAR(1 BYTE),
    ASSIGNED_INDICATOR CHAR(1 BYTE),
    IN_TRUST_INDICATOR CHAR(1 BYTE),
    DIVORCE_CASE_INDICATOR CHAR(1 BYTE),
    POA_COP_INDICATOR CHAR(1 BYTE),
    THAMES_URN_WITH_ROLE_SUFFIX VARCHAR2(39 BYTE),
    THAMES_LEGAL_OWNERSHIP_IND CHAR(1 BYTE),
    PRODUCT_HOLDING_ROLE_TYPE VARCHAR2(21 BYTE),
    OWNERSHIP_SPLIT_PERCENTAGE NUMBER(3),
    SOURCE_SYSTEM VARCHAR2(3 BYTE),
    TITLE VARCHAR2(50 BYTE),
    FIRST_NAME VARCHAR2(50 BYTE),
    MIDDLE_INITIAL VARCHAR2(50 BYTE),
    SURNAME VARCHAR2(50 BYTE),
    GENDER CHAR(1 BYTE),
    BIRTH_DATE DATE,
    DEATH_INDICATOR CHAR(1 BYTE),
    DEATH_RECORD_DATE DATE,
    NATIONAL_INSURANCE_NUMBER VARCHAR2(9 BYTE),
    GONE_AWAY_INDICATOR CHAR(1 BYTE),
    ADDRESS_LINE_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_3 VARCHAR2(50 BYTE),
    ADDRESS_LINE_4 VARCHAR2(50 BYTE),
    ADDRESS_LINE_5 VARCHAR2(50 BYTE),
    POST_CODE VARCHAR2(12 BYTE),
    COUNTRY VARCHAR2(50 BYTE),
    OVERSEAS_ADDRESS_INDICATOR CHAR(1 BYTE),
    ORGANISATION_NAME VARCHAR2(50 BYTE),
    TPDB_PROCESSED_IDENTIFIER CHAR(2 BYTE),
    CLEANSING_STATUS VARCHAR2(30 BYTE),
    CATEGORY VARCHAR2(50 BYTE),
    SCHEME_NAME VARCHAR2(50 BYTE),
    STG_CREATE_DATE_TIME DATE,
    STG_UPDATE_DATE_TIME DATE,
    LAST_UPDATED_DATE_TIME DATE
    TABLESPACE TPDBS01A_DATA
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    CREATE UNIQUE INDEX TPD_STG_TL_SF_LEGAL_OWNER_PK ON TPD_STG_TL_SF_LEGAL_OWNER
    (THAMES_URN_WITH_ROLE_SUFFIX)
    LOGGING
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    NOPARALLEL;
    ALTER TABLE TPD_STG_TL_SF_LEGAL_OWNER ADD (
    CONSTRAINT TPD_STG_TL_SF_LEGAL_OWNER_PK
    PRIMARY KEY
    (THAMES_URN_WITH_ROLE_SUFFIX)
    USING INDEX
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    ));

    > If indexes don't help, is the only way to gain REAL
    performance gain on this type of query is to
    partition the table
    If a Full Table Scan on a table takes "too long" (and
    this is purely subjective - "too long" is different
    for every problem) and indexes can't help, and we
    need <100% of the rows, and if partitioning will give
    us the performance we desire, is it OK do it ? Also
    would STG_UPDATE_DATE_TIME be the best column to do a
    index partion ?
    For this type of query, partitioning on STG_UPDATE_DATE_TIME would be good.
    However, partitioning is not done just for one query. It has to fit in your total design. For example, if you are also doing queries with a predicate like <column with a local unique index but not the partition key> = <constant>, it would have to visit all partitions instead of just one, and those queries would take much longer to execute. You can make the index global, but there all kind of maintenance issues with that. In short: be careful about partitioning and think it through first.
    > But is it a good option to partition tables with
    total no. of rows between 2 million and 5 million ? I
    thought partitioning is better done for tables > 20
    million.
    Please throw some light on that.
    Generally, partitioning is done on bigger tables, yes. But it is not about some specific number of rows. You partition a table when all forecasted use of the table is known, so you can make a good judgement which usages will benefit, which ones won't be affected and which ones are likely to suffer. When the benefits outweigh the disadvantages, you partition...
    Above I had an example about queries that are going to suffer. Partitioning is beneficial for example when once in some period you'd have to delete A LOT of old rows. Or when you have some data warehousing queries that need like 10% of only the most recent data in a huge table.
    The decision is yours.
    Regards,
    Rob.

  • Help needed on creating a SAP query

    Hi All,
    Can somebody give me the step by step procedures of creating a SAP query and Infoset.
    My requirement is to display asset master details with Asset number or Asset class as input.
    Any pointers or links to create an infoset and query will br highly helpful.
    Thanks,
    Arun

    Here are couple of fields you might be needed :
    AGKO     Cleared Accounts
    ANAR     Asset Types
    ANAT     Asset type text
    ANEK     Document Header Asset Posting
    ANEP     Asset Line Items
    ANEV     Asset downpymt settlement
    ANKT     Asset classes- Description
    ANLA     Asset Master Record Segment
    ANLB     Depreciation terms
    ANLC     Asset Value Fields
    ANLH     Main asset number
    AT02T     Transaction Activity Category- Description
    AT02A     Transaction Code for Menu TIMN
    AT10     Transaction type
    AT10T     Name of Transaction Type
    BKDF     Document Header Supplement for Recurring Entry
    BKORM     Accounting Correspondence Requests
    BKPF     Accounting Document Header
    BLPK     Document log header
    BLPP     Document log item
    BLPR     Document Log Index and Planned Order (Backflush)
    BNKA     Bank master record
    BP000     Business Partner Master (General Data)
    BPBK     Doc.Header Controlling Obj.
    BPEG     Line Item Total Values Controlling Obj.
    BPEJ     Line Item Annual Values Controlling Obj.
    BPEP     Line Item Period Values Controlling Obj.
    BPGE     Totals Record for Total Value Controlling obj.
    BPJA     Totals Record for Annual Total Controlling Obj.
    BSAD     Accounting- Secondary Index for Customers (Cleared Items)
    BSAK     Accounting- Secondary Index for Vendors (Cleared Items)
    BSAS     Accounting- Secondary Index for G/L Accounts (Cleared Items)
    BSEC     One-Time Account Data Document Segment
    BSEG     Accounting Document Segment
    BSID     Accounting- Secondary Index for Customers
    BSIK     Accounting- Secondary Index for Vendors
    BSIM     Secondary Index, Documents for Material
    BSIS     Accounting- Secondary Index for G/L Accounts
    CEPC     Profit Center Master Data Table
    CEPCT     Texts for Profit Center Master Data
    COBRA     Settlement Rule for Order Settlement
    COBRB     Distribution Rules Settlement Rule Order Settlement
    COKA     CO Object- Control Data for Cost Elements
    COSP     CO Object- Cost Totals for External Postings
    COSS     CO Object- Cost Totals for Internal Postings
    CRCO     Assignment of Work Center to Cost Center
    CSKA     Cost Elements (Data Dependent on Chart of Accounts)
    CSKB     Cost Elements (Data Dependent on Controlling Area)
    CSLA     Activity master
    FEBEP     Electronic Bank Statement Line Items
    FPLA     Billing Plan
    FPLT     Billing Plan- Dates
    GLPCT     EC-PCA- Totals Table
    KNA1     General Data in Customer Master
    KOMK     Pricing Communication Header
    MAHNV     Management Records for the Dunning Program
    REGUT     TemSe - Administration Data
    SKA1     G/L Account Master (Chart of Accounts)
    SKAT     G/L Account Master Record (Chart of Accounts- Description)
    SKB1     G/L account master (company code)
    T003T     Document Type Texts
    T007S     Tax Code Names
    T087J     Text
    TAPRFT     Text tab. for investment profile
    TKA01     Controlling Areas
    TKA09     Basic Settings for Versions
    TKVS     CO Versions
    TZB0T     Flow types text table
    TZPAT     Financial Assets Management product type texts
    VBSEGS     Document Segment for G/L Accounts Document Parking
    VTBFHA     Transaction
    VTBFHAPO     Transaction Flow
    VTBFHAZU     Transaction Activity
    VTBFINKO     Transaction Condition
    VTIDERI     Master Data Listed Options and Futures
    VTIFHA     Underlying transaction
    VTIFHAPO     Underlying transaction flows
    VTIFHAZU     Underlying transaction status table
    VTIOF     Options Additional Data
    VWPANLA     Asset master for securities

  • Help needed on writing a SQL query

    Here is my table that shows records of 3 ORDER_ID (10, 20 and 30). All I need to do is, pick the first record of each order_id and check the event_id, if the event_id is same for the next record, ignore it, else show it and ignore rest all records for that order_id. This way my query output will show only two records for each ORDER_ID. Query should produce records that are in BOLD in the sample data. (Database - 11g)
    Thanks for your help in advance
    ORDER_ID     EVENT_ID     EVNT_DATE     STATE_CODE
    *10     16937555     20100212     COMPLETE*
    10     16937555     20100212     ACTIVE
    *10     16308004     20100129     OCCURRED*
    10     16131904     20100125     ACTIVE
    10     16270684     20100128     OCCURRED
    10     14899116     20091213     ACTIVE
    10     16085672     20100123     COMPLETE
    10     16085673     20100123     OCCURRED
    10     14899119     20100123     COMPLETE
    10     14899120     20100123     COMPLETE
    *20     17134164     20100223     COMPLETE*
    20     17134164     20100223     ACTIVE
    20     17134164     20100223     STARTED
    *20     15479131     20100105     OCCURRED*
    20     15478409     20100105     OCCURRED
    20     15478408     20100105     ACTIVE
    20     15119404     20100105     COMPLETE
    20     14346123     20091129     ACTIVE
    20     15467821     20100104     OCCURRED
    20     14346125     20091216     COMPLETE
    20     14346126     20091215     COMPLETE
    20     14346126     20091214     COMPLETE
    *30     18814670     20100412     COMPLETE*
    30     18814670     20100412     ACTIVE
    *30     18029509     20100320     OCCURRED*
    30     16853720     20100211     ACTIVE
    30     17965764     20100319     OCCURRED
    30     16386708     20100211     COMPLETE
    30     16804451     20100211     OCCURRED
    30     15977897     20100121     ACTIVE
    Edited by: sarvan on Aug 12, 2011 7:16 AM

    try this [Not fully tested]
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE    11.2.0.2.0      Production
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    Elapsed: 00:00:00.00
    SQL> SELECT *
      2    FROM (SELECT order_id, event_id, evnt_date, state_code, next_evntid,
      3                 ROW_NUMBER () OVER (PARTITION BY event_id ORDER BY NULL)
      4                                                                       AS rownm
      5            FROM (WITH t AS
      6                       (SELECT 10 AS order_id, 16937555 AS event_id,
      7                               20100212 AS evnt_date, 'COMPLETE' AS state_code
      8                          FROM DUAL
      9                        UNION ALL
    10                        SELECT 10, 16937555, 20100212, 'ACTIVE'
    11                          FROM DUAL
    12                        UNION ALL
    13                        SELECT 10, 16308004, 20100129, 'OCCURRED'
    14                          FROM DUAL
    15                        UNION ALL
    16                        SELECT 10, 16131904, 20100125, 'ACTIVE'
    17                          FROM DUAL
    18                        UNION ALL
    19                        SELECT 10, 16270684, 20100128, 'OCCURRED'
    20                          FROM DUAL
    21                        UNION ALL
    22                        SELECT 20, 17134164, 20100223, 'COMPLETE'
    23                          FROM DUAL
    24                        UNION ALL
    25                        SELECT 20, 17134164, 20100223, 'ACTIVE'
    26                          FROM DUAL
    27                        UNION ALL
    28                        SELECT 20, 17134164, 20100223, 'STARTED'
    29                          FROM DUAL
    30                        UNION ALL
    31                        SELECT 20, 15479131, 20100105, 'OCCURRED'
    32                          FROM DUAL)  -- End of test data
    33                  SELECT order_id, event_id, evnt_date, state_code,
    34                         LEAD (event_id, 1, 0) OVER (PARTITION BY order_id ORDER BY NULL)
    35                                                                 AS next_evntid
    36                    FROM t)
    37           WHERE event_id = next_evntid)
    38   WHERE rownm <= 2
    39  /
      ORDER_ID   EVENT_ID  EVNT_DATE STATE_CO NEXT_EVNTID      ROWNM
            10   16937555   20100212 COMPLETE    16937555          1
            20   17134164   20100223 COMPLETE    17134164          1
            20   17134164   20100223 ACTIVE      17134164          2
    Elapsed: 00:00:00.00
    SQL> PS - You should seriously think about ordering the data before you do this kind off operations.
    Edited by: Sri on Aug 12, 2011 9:12 AM

  • Sql query ..need idea to write complex query

    Hi there,
    I have assigned the task to write a sql query to get the output as the below stored proc does.
    In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
    Is anyone could help me?
    Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
    create or replace PROCEDURE vpp_station_summary_report (
    in_user_id                     IN  VARCHAR2,
    in_report_id      IN  NUMBER,
    in_time_from                IN      vppstation.avi_status_history.status_eff_date%TYPE,
    in_time_to                  IN  vppstation.avi_status_history.status_eff_date%TYPE,
    result                               OUT SYS_REFCURSOR)
    AS
    CURSOR station_loop IS
       SELECT ash.station_id,
              ash.avi_id,
              ash.state_id,
              ash.state_eff_date
       FROM   vppstation.avi_state_history ash
       JOIN   vpproadside.vpp_report_stations
         ON   vpp_report_stations.station_id             = ash.station_id
        AND   vpp_report_stations.vpp_report_seq_number  = in_report_id
       WHERE  ash.state_eff_date BETWEEN in_time_from AND in_time_to
       ORDER BY ash.station_id,
                ash.avi_id,
                ash.state_eff_date,
                ash.ash_id;
    -- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
    -- in_time_from
    CURSOR entry_state (
              state_station_id vppstation.avi_state_history.station_id%TYPE,
              state_avi_id     vppstation.avi_state_history.avi_id%TYPE,
              state_state_date vppstation.avi_state_history.state_eff_date%TYPE
    IS
       SELECT ash.state_id
       FROM   vppstation.avi_state_history ash
       WHERE  ash.station_id = state_station_id
         AND  ash.avi_id = state_avi_id
         AND  ash.state_eff_date < state_state_date
       ORDER BY ash.state_eff_date DESC,
                ash.ash_id DESC;
    current_station_id         vppstation.avi_state_history.station_id%TYPE;
    current_avi_id             vppstation.avi_state_history.avi_id%TYPE;
    current_state_id           vppstation.avi_state_history.state_id%TYPE;
    current_state_eff_date     vppstation.avi_state_history.state_eff_date%TYPE;
    period_length NUMBER;
    next_station_id     vppstation.avi_state_history.station_id%TYPE;
    next_avi_id         vppstation.avi_state_history.avi_id%TYPE;
    next_state_id       vppstation.avi_state_history.state_id%TYPE;
    next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
    station_open_total       NUMBER;
    station_closed_total     NUMBER;
    station_all_report_total NUMBER;
    current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
    state_open       vppstation.avi_control_state_code.state_id%TYPE;
    state_closed     vppstation.avi_control_state_code.state_id%TYPE;
    state_all_report vppstation.avi_control_state_code.state_id%TYPE;
    BEGIN
    SELECT state_id
    INTO   state_open
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'E'
    AND    state_active_ind = 'A';
    SELECT state_id
    INTO   state_closed
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'D'
    AND    state_active_ind = 'A';
    SELECT state_id
    INTO   state_all_report
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'S'
    AND    state_active_ind = 'A';
    current_station_id := -1;
    current_avi_id     := -1;
    current_state_id   := state_closed;
    current_state_eff_date := in_time_from;
    station_open_total       := 0.0;
    station_closed_total     := 0.0;
    station_all_report_total := 0.0;
    -- for starters - ensure that there is report data for all requested stations...
    INSERT INTO vpproadside.vpp_station_summary
          vpp_report_seq_number,
          station_id,
          station_name,
          ln_number,
          lane_name,
          station_open,
          station_close,
          station_all_report,
          station_total
      SELECT in_report_id,
             vrs.station_id,
             si.station_name,
             l.ln_number,
             l.lane_name,
             0.0,
             0.0,
             0.0,
             0.0
      FROM vpproadside.vpp_report_stations vrs
      LEFT OUTER JOIN  vpproadside.stations_installed si
        ON  si.station_id = vrs.station_id
      LEFT OUTER JOIN vppstation.lane_name l
        ON l.station_id = vrs.station_id
      WHERE vrs.vpp_report_seq_number  = in_report_id;
    -- loop over state history and update information for all stations found
    OPEN station_loop;
    LOOP
      FETCH station_loop
      INTO
            next_station_id,
            next_avi_id,
            next_state_id,
            next_state_eff_date;
      IF station_loop%NOTFOUND THEN
        next_station_id := -1;
        next_avi_id     := -1;
      END IF;
      -- if station/avi has changed take the end of the report period
      IF    (next_station_id <> current_station_id)
         OR (next_avi_id     <> current_avi_id)
      THEN
        period_length := in_time_to - current_state_eff_date;
      ELSE
        -- otherwise the start of the next period marks the end of the current period
        period_length := next_state_eff_date - current_state_eff_date;
      END IF;
      -- if we have a real station id then do some work...
      IF (current_station_id <> -1) THEN
        -- determine which category the period fits to and apply calculation
        IF current_state_id = state_open THEN
          station_open_total := station_open_total + period_length - 1;
        ELSIF current_state_id = state_closed THEN
          station_closed_total := station_closed_total + period_length - 1;
        ELSIF current_state_id = state_all_report THEN
          station_all_report_total := station_all_report_total + period_length - 1;
        ELSE
          RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
        END IF;
        -- if the station/avi has changed then commit changes to db
        IF    (next_station_id <> current_station_id)
           OR (next_avi_id     <> current_avi_id)
        THEN
          UPDATE vpproadside.vpp_station_summary
          SET
              station_open       = station_open_total,
              station_close      = station_closed_total,
              station_all_report = station_all_report_total
          WHERE vpp_report_seq_number = in_report_id
          AND   station_id = current_station_id
          AND   ln_number  = current_avi_id;
          -- reset counts
          station_open_total       := 0.0;
          station_closed_total     := 0.0;
          station_all_report_total := 0.0;
        END IF;
      END IF;
      -- if we got past the last record then stop processing
      EXIT WHEN station_loop%NOTFOUND;
      -- if the station/avi is changing, get the state that was 'current' at in_time_from
      IF    (next_station_id <> current_station_id)
         OR (next_avi_id     <> current_avi_id)
      THEN
        current_state_eff_date := in_time_from;
        OPEN entry_state (
               next_station_id,
               next_avi_id,
               in_time_from
        FETCH entry_state
        INTO  current_state_id;
        IF entry_state%NOTFOUND THEN
          current_state_id := state_closed;
        END IF;
        CLOSE entry_state;
        period_length := next_state_eff_date - current_state_eff_date;
        IF current_state_id = state_open THEN
          station_open_total := station_open_total + period_length;
        ELSIF current_state_id = state_closed THEN
          station_closed_total := station_closed_total + period_length;
        ELSIF current_state_id = state_all_report THEN
          station_all_report_total := station_all_report_total + period_length;
        ELSE
            RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
        END IF;
      END IF;
      current_state_id       := next_state_id;
      current_state_eff_date := next_state_eff_date;
      current_station_id     := next_station_id;
      current_avi_id         := next_avi_id;
    END LOOP;
    CLOSE station_loop;
    -- update the totals for the percentage calculation
    UPDATE vpproadside.vpp_station_summary
    SET
           station_total = station_open + station_close+ station_all_report
    WHERE   vpp_report_seq_number = in_report_id;
    -- 'fix' the totals that are still zero to avoid divide by zero errors...
    --       note: all the percentages will still come out as zero since the total
    --             was zero
    UPDATE vpproadside.vpp_station_summary
    SET
           station_total = 1.0
    WHERE  vpp_report_seq_number = in_report_id
    AND    station_total = 0.0;
    OPEN result FOR
    SELECT station_name "Site Name",
           lane_name    "Lane Name",
           TO_CHAR((station_open       / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
           TO_CHAR((station_close      / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
           TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
    FROM vpproadside.vpp_station_summary
    WHERE vpp_report_seq_number = in_report_id
    ORDER BY UPPER(station_name),
             UPPER(lane_name);
    DELETE FROM vpproadside.vpp_station_summary
    WHERE vpp_report_seq_number = in_report_id;
    END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
    Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
    Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
    Edited by: Indhu Ram on Mar 10, 2010 11:12 AM

    Exactly dont know what you are asking for but I can suggest you some tips here
    - If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
    SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
    FROM table1, table2
    WHERE
    <some conditions>
    - If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
    something like this
    SELECT function_name(parameter1, parameter2....) from dual
    Hope this will help

  • Help need to build a report query

    Hi all
    I am using reports 6i and 10 g db.
    I am asked to generate letter format report. The content of letter format will be from employee_deschange_details.edcd_desc field .
    The parameter i have to pass is emp_code and dsm_code. Based on it the content should be displayed.
    In employee_deschange_detail.edcd_desc field has letter content in a particular way as follows
    for example
    It is my pleasure to inform you that you have been promoted to the position %DESIGNATION effective from %EFFECTIVE_DATE.The %DESIGNATION and %EFFECTIVE_DATE are identifier which should get replaced by actual value.
    The identifiers and its actual value is stored in employee_deschange_detail.edcd_title_name and employee_deschange_detail.edcd_param_value respectively.
    the value are stored like |%DESIGNATION|%EFFECTIVE_DATE| in edcd_title_name and in
    edcd_param_value the data stores like |GM-FIN|21-JUN-2010|
    The user can add extra letter content through a form ,so that the content's may get vary.
    Thanks,
    Rincy

    Hi Arif
    If have planned to create PLSQL query as follows but it give message in compilation
    Error 0 at line,column 0
    REP-0737: Should be a function with return type 'ref cursor'
    I havent used plSql query yet, not able to proceed. Please go through and please suggest a best way .
    function QR_1RefCurDS return cur_ref_type
    is
    cursor cur_edcd is
    select edcd_code,decode(instr(edcd_desc,'%TABLE1'),0,edcd_desc,substr(edcd_desc,1,instr(edcd_desc,'%TABLE1')-1)) part1,
    decode (instr(edcd_desc,'%TABLE1'),0,null,substr(edcd_desc,instr(edcd_desc,'%TABLE1')+length('%TABLE1'),length(edcd_desc))) part2,edcd_serial
    from employee_deschange_details
    where edcd_orgn=:p_orgn
    and (edcd_ctry=:p_ctry or :p_ctry is null)
    and (edcd_loc=:p_loc or :p_loc ia null)
    and (edcd_oru=:p_oru or :p_oru is null)
    and (edcd_code=:deschange_code or :deschange_code is null)
    and (edcd_emp_code=:employee_code or :employee_code is null)
    order by edcd_emp_code,edcd_serial desc;
    v_srl number;
    v_part1 varchar2(4000);
    v_part2 varchar2(4000);
         Cursor cur_param_value
         is
         select
    substr(edcd_title_name,
      instr (edcd_title_name, '|', 1, level)+1,
      instr (edcd_title_name, '|', 1, level+1) - instr (edcd_title_name, '|', 1, level) -1) res,
    substr(edcd_param_value,
      instr (edcd_param_value, '|', 1, level)+1,
      instr (edcd_param_value, '|', 1, level+1) - instr (edcd_param_value, '|', 1, level) -1) result
    from   (select edcd_title_name,edcd_param_value from employee_deschange_details where edcd_emp_code =:employee_code
       and edcd_code=:deschange_code and edcd_serial=v_srl)
    connect by level < length(edcd_title_name)-length(replace(edcd_title_name,'|',''))
    Order by length(substr(edcd_title_name,
      instr (edcd_title_name, '|', 1, level)+1,
      instr (edcd_title_name, '|', 1, level+1) - instr (edcd_title_name, '|', 1, level) -1));
    TYpe cur_ref_type is ref cursor;
    cur_ref cur_ref_type;
    begin
      open cur_edcd ;
      loop
      fetch cur_edcd into v_part1,v_part2,v_srl;
      if cur_edcd%found then
            open cur_param_value;
            loop
            fetch cur_param_value into v_title,v_title_value;
            if cur_param_value%found then
                      V_part1=replace(v_part1,v_title,v_title_value);
                      V_part2=replace(v_part2,v_title,v_title_value);
            end if;
            exit when cur_param_value%notfound;
            end loop;
      end if;     
      exit when cur_edcd%notfound;
      end loop;
      close cur_param_value;
      close cur_edcd;
      open cur_ref for (select v_part1,v_part2 from dual);
      return(cur_ref);
    end;Thanks,
    Rincy
    Edited by: Rincy Binu on Jul 4, 2010 1:00 PM
    Edited by: Rincy Binu on Jul 4, 2010 1:01 PM

  • Help needed in the a sql query

    hi,
    i have small but tricky piece of requirements,
    following is the input
    Id     id_type     id_level     id_name
    1     F     A_1     Beta1
    2     W     A_1     Beta2
    3     W     A_1     Beta3
    4     L     A_1     Alpha0
    5     W     A_1     Beta4
    6     W     A_1     Beta5
    now whenever
    Id_level = A_1, and id_name = Alpha0 and id_type = L then               
    id_level = B_1               
    and the coming next 2 levels after this should have id_level C_1
    the output should be as follows
    Id     id_type     id_level     id_name
    1     F     A_1     Beta1
    2     W     A_1     Beta2
    3     W     A_1     Beta3
    4     L     B_1     Alpha0
    5     W     C_1     Beta4
    6     W     C_1     Beta5
    kindly let me know if this could be possible in sql,
    if i am missing something here plz highlight it to me,
    kindly give me some tips or hints,thanks and regards
    nic

    SQL> WITH Test_Data AS (
      2    SELECT 1 AS Id, 'F' AS Id_Type, 'A_1' AS Id_Level, 'Beta1' AS Id_Name FROM Dual UNION ALL
      3    SELECT 2,       'W',            'A_1',             'Beta2'            FROM Dual UNION ALL
      4    SELECT 3,       'W',            'A_1',             'Beta3'            FROM Dual UNION ALL
      5    SELECT 6,       'L',            'A_1',             'Alpha0'           FROM Dual UNION ALL
      6    SELECT 8,       'W',            'A_1',             'Beta4'            FROM Dual UNION ALL
      7    SELECT 10,      'W',            'A_1',             'Beta4'            FROM Dual UNION ALL
      8    SELECT 11,      'W',            'A_1',             'Beta5'            FROM Dual
      9  )
    10  SELECT Id, Id_Type,
    11    CASE WHEN Id_Level = 'A_1' AND Id_Name = 'Alpha0' AND Id_Type = 'L'
    12           THEN 'B_1'
    13         WHEN COUNT(CASE WHEN Id_Level = 'A_1' AND Id_Name = 'Alpha0' AND Id_Type = 'L' THEN 1 ELSE NULL END)
    14                OVER(ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) = 0
    15           THEN Id_Level
    16         WHEN COUNT(CASE WHEN Id_Level = 'A_1' AND Id_Name = 'Alpha0' AND Id_Type = 'L' THEN 1 ELSE NULL END)
    17                OVER(ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) > 0
    18           THEN 'C_1'
    19     END AS Id_Level,
    20     Id_Name
    21  FROM Test_Data
    22  ORDER BY Id;
            ID I ID_ ID_NAM
             1 F A_1 Beta1
             2 W A_1 Beta2
             3 W A_1 Beta3
             6 L B_1 Alpha0
             8 W C_1 Beta4
            10 W C_1 Beta4
            11 W C_1 Beta5
    7 rows selected.Regards,
    Dima

  • Help needed with Spry Grow/Shrink Query!

    Dear All,
    I am attempting to use the new spry effects in cs3 to grow (
    and the optionally shrink) a city map for users.
    My difficulty is that if you use an image at the correct 100%
    size, but want to grow it from 10%, the 100% image displays as
    default when you load the page, then once clicked it reszies up
    from 10%.
    I cant use a 10% image as my start point, because then the
    'grown' map is illegible.
    Any tips?
    Cheers
    Si

    Use OnLoad with grow and set both size fields to 10% with
    milliseconds set to 0
    Then onClick toggle grow from 100% (don't know why) to the
    Pixel size you want for the second field.

  • How to store data from a complex query and only fresh hourly or daily?

    We have a report which runs quite slow (1-2 minutes) because the query is quite complicate, so we would like to run this query daily only and store in a table so for those procedures that need to use this complex query as a subquery, can just join to this table directly to get results.
    However, I am not sure what kind of object I should use to store data for this complex query. Is data in global temp table only persist within transaction? I need something that can persist the data and be access by procedures.
    Any suggestions are welcome,
    Cheers

    Thank you for your reply. I looked at the materialized view earlier on, but have some difficulties to use it. So I have some questions here:
    1.The complex query is not a sum or aggregate functions, it just need to get data from different tables based on different conditions, in this case is it still appropriate to use meterialized view?
    2.If it is, I created one, but how to use it in my procedure? From the articles I read, it seems I can't just query from this view directly. So do I need to keep the complex query in my procedure and how the procedure will use the meterialized view instead?
    3. I also put the complex query in a normal view, then create a materialized view for this normal view (I expect the data from the complex query will be cache here), then in the procedure I just select * from my_NormalView, but it takes the same time to run even when I set the QUERY_REWRITE_ENABLED to true in the alter session. So I am not sure what else I need to do to make sure the procedure use the materialized view instead of the normal view. Can I query from the Materialized View directly?
    Below in the code I copied from one of the article to create the materialized view based on my normal view:
    CREATE MATERIALIZED VIEW HK3ControlDB.MW_RIRating
    PCTFREE 5 PCTUSED 60
    TABLESPACE "USERS"
    STORAGE (INITIAL 50K NEXT 50K)
    USING INDEX STORAGE (INITIAL 25K NEXT 25K)
    REFRESH START WITH ROUND(SYSDATE + 1) + 11/24
    NEXT NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 15/24
    enable query rewrite
    AS SELECT * FROM HK3ControlDB.VW_RIRating;
    Cheers

  • Complex Query which needs tuning

    Hello :
    I have a complex query that needs to be tuned. I have little experience in tuning the sql and hence taking the help of your guys.
    The Query is as given below:
    Database version 11g
    SELECT DISTINCT P.RESPONSIBILITY, P.PRODUCT_MAJOR, P.PRODUCT_MINOR,
    P.PRODUCT_SERIES, P.PRODUCT_CATEGORY AS Category1, SO.REGION_CODE,
    SO.STORE_CODE, S.Store_Name, SOL.PRODUCT_CODE, PRI.REPLENISHMENT_TYPE,
    PRI.SUPPLIER_CODE,
    SOL.SOLD_WITH_NIC, SOL.SUGGESTED_PRICE,
    PRI.INVOICE_COST, SOL.FIFO_COST,
    SO.ORDER_TYPE_CODE, SOL.DOCUMENT_NUM,
    SOS.SLSP_CD, '' AS FNAME, '' AS LNAME,
    SOL.PRICE_EXCEPTION_CODE, SOL.AS_IS,
    SOL.STATUS_DATE,
    Sum(SOL.QUANTITY) AS SumOfQUANTITY,
    Sum(SOL.EXTENDED_PRICE) AS SumOfEXTENDED_PRICE
    --Format([SALES_ORDER].[STATUS_DATE],"mmm-yy") AS [Month]
    FROM PRODUCT P,
    PRODUCT_MAJORS PM,
    SALES_ORDER_LINE SOL,
    STORE S,
    SALES_ORDER SO,
    SALES_ORDER_SPLITS SOS,
    PRODUCT_REGIONAL_INFO PRI,
    REGION_MAP R
    WHERE P.product_major = PM.PRODUCT_MAJOR
    and SOL.PRODUCT_CODE = P.PRODUCT_CODE
    and SO.STORE_CODE = S.STORE_CODE
    AND SO.REGION_CODE = S.REGION_CODE
    AND SOL.REGION_CODE = SO.REGION_CODE
    AND SOL.DOCUMENT_NUM = SO.DOCUMENT_NUM
    AND SOL.DELIVERY_SEQUENCE_NUM = SO.DELIVERY_SEQUENCE_NUM
    AND SOL.STATUS_CODE = SO.STATUS_CODE
    AND SOL.STATUS_DATE = SO.STATUS_DATE
    AND SO.REGION_CODE = SOS.REGION_CODE
    AND SO.DOCUMENT_NUM = SOS.DOCUMENT_NUM
    AND SOL.PRODUCT_CODE = PRI.PRODUCT_CODE
    AND PRI.REGION_CODE = R.CORP_REGION_CODE
    AND SO.REGION_CODE = R.DS_REGION_CODE
    AND P.PRODUCT_MAJOR In ('STEREO','TELEVISION','VIDEO')
    AND SOL.STATUS_CODE = 'D'
    AND SOL.STATUS_DATE BETWEEN '01-JUN-09' AND '30-JUN-09'
    AND SO.STORE_CODE NOT IN
    ('10','20','30','40','70','91','95','93','94','96','97','98','99',
    '9V','9W','9X','9Y','9Z','8Z',
    '8Y','92','CZ','FR','FS','FT','FZ','FY','FX','FW','FV','GZ','GY','GU','GW','GV','GX')
    GROUP BY
    P.RESPONSIBILITY, P.PRODUCT_MAJOR, P.PRODUCT_MINOR, P.PRODUCT_SERIES, P.PRODUCT_CATEGORY,
    SO.REGION_CODE, SO.STORE_CODE, /*S.Short Name, */
    S.Store_Name, SOL.PRODUCT_CODE,
    PRI.REPLENISHMENT_TYPE, PRI.SUPPLIER_CODE,
    SOL.SOLD_WITH_NIC, SOL.SUGGESTED_PRICE, PRI.INVOICE_COST,
    SOL.FIFO_COST, SO.ORDER_TYPE_CODE, SOL.DOCUMENT_NUM,
    SOS.SLSP_CD, '', '', SOL.PRICE_EXCEPTION_CODE,
    SOL.AS_IS, SOL.STATUS_DATE
    Explain Plan:
    SELECT STATEMENT, GOAL = ALL_ROWS               Cost=583     Cardinality=1     Bytes=253
    HASH GROUP BY               Cost=583     Cardinality=1     Bytes=253
    FILTER                         
    NESTED LOOPS               Cost=583     Cardinality=1     Bytes=253
    HASH JOIN OUTER               Cost=582     Cardinality=1     Bytes=234
    NESTED LOOPS                         
    NESTED LOOPS               Cost=571     Cardinality=1     Bytes=229
    NESTED LOOPS               Cost=571     Cardinality=1     Bytes=207
    NESTED LOOPS               Cost=569     Cardinality=2     Bytes=368
    NESTED LOOPS               Cost=568     Cardinality=2     Bytes=360
    NESTED LOOPS               Cost=556     Cardinality=3     Bytes=435
    NESTED LOOPS     Cost=178     Cardinality=4     Bytes=336
    NESTED LOOPS          Cost=7     Cardinality=1     Bytes=49
    HASH JOIN               Cost=7     Cardinality=1     Bytes=39
    VIEW     Object owner=CORP     Object name=index$_join$_015     Cost=2     Cardinality=3     Bytes=57
    HASH JOIN                         
    INLIST ITERATOR                         
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRODMJR_PK     Cost=0     Cardinality=3     Bytes=57
    INDEX FAST FULL SCAN     Object owner=CORP     Object name=PRDMJR_PR_FK_I     Cost=1     Cardinality=3     Bytes=57
    VIEW     Object owner=CORP     Object name=index$_join$_016     Cost=4     Cardinality=37     Bytes=740
    HASH JOIN                         
    INLIST ITERATOR                         
    INDEX RANGE SCAN     Object owner=CORP     Object name=PRDMNR1     Cost=3     Cardinality=37     Bytes=740
    INDEX FAST FULL SCAN     Object owner=CORP     Object name=PRDMNR_PK     Cost=4     Cardinality=37     Bytes=740
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRODMJR_PK     Cost=0     Cardinality=1     Bytes=10
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=PRODUCTS     Cost=171     Cardinality=480     Bytes=16800
    INDEX RANGE SCAN     Object owner=CORP     Object name=PRD2     Cost=3     Cardinality=681     
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=SALES_ORDER_LINE     Cost=556     Cardinality=1     Bytes=145
    BITMAP CONVERSION TO ROWIDS                         
    BITMAP INDEX SINGLE VALUE     Object owner=DS     Object name=SOL2               
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=SALES_ORDER     Cost=4     Cardinality=1     Bytes=35
    INDEX RANGE SCAN     Object owner=DS     Object name=SO1     Cost=3     Cardinality=1     
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=REGION_MAP     Cost=1     Cardinality=1     Bytes=4
    INDEX RANGE SCAN     Object owner=DS     Object name=REGCD     Cost=0     Cardinality=1     
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=PRODUCT_REGIONAL_INFO     Cost=2     Cardinality=1     Bytes=23
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRDRI_PK     Cost=1     Cardinality=1     
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=BI_STORE_INFO_PK     Cost=0     Cardinality=1     
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=BI_STORE_INFO     Cost=1     Cardinality=1     Bytes=22
    VIEW     Object owner=DS     cost=11     Cardinality=342     Bytes=1710
    HASH JOIN               Cost=11     Cardinality=342     Bytes=7866
    MAT_VIEW ACCESS FULL     Object owner=CORP     Object name=STORE_CORP     Cost=5     Cardinality=429     Bytes=3003
    NESTED LOOPS               Cost=5     Cardinality=478     Bytes=7648
    MAT_VIEW ACCESS FULL     Object owner=CORP     Object name=STORE_GROUP     Cost=5     Cardinality=478     Bytes=5258
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=STORE_REGIONAL_INFO_PK     Cost=0     Cardinality=1     Bytes=5
    INDEX RANGE SCAN     Object owner=DS     Object name=SOS_PK     Cost=2     Cardinality=1     Bytes=19
    Regards,
    BMP

    First thing that i notice in this query is you are Using Distinct as well as Group by.
    Your group by will always give you distinct results ,then again why do you need the Distinct?
    For example
    WITH t AS
         (SELECT 'clm1' col1, 'contract1' col2,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1' , 'contract1' ,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1', 'contract2',10
            FROM DUAL
          UNION ALL
          SELECT 'clm2', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm3', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm4', 'contract2',10
            FROM DUAL)
    SELECT  distinct col1,col2,sum(value) from t
    group by col1,col2Is always same as
    WITH t AS
         (SELECT 'clm1' col1, 'contract1' col2,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1' , 'contract1' ,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1', 'contract2',10
            FROM DUAL
          UNION ALL
          SELECT 'clm2', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm3', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm4', 'contract2',10
            FROM DUAL)
    SELECT  col1,col2,sum(value) from t
    group by col1,col2And also
    AND SOL.STATUS_DATE BETWEEN '01-JUN-09' AND '30-JUN-09'It would be best to use a to_date when hard coding your dates.
    Edited by: user5495111 on Aug 6, 2009 1:32 PM

  • Trying to form complex query - need help

    I have a fairly complex query that I need to join the results of to show actual and goal by day. The actuals are an aggregation of records that get put in every day, while the targets are a single entry in range format indicating an active range for which the target applies. I'm working on a query that will put things together by month and I'm running into a snag. Can someone please point out where appropriate naming needs to go to get this to come together?
    This one works:
    (select DATE_INDEX, SUM(LDS) as TTLLDS, SUM(TONS) as TTLTONS from
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC)
      group by DATE_INDEX)Now I need to add in the following query:
    select (u.MACH_TPH_D+u.MACH_TPH_N)/2 as MTPH_TGT, (u.LABOR_TPH_D+u.LABOR_TPH_N)/2 as LTPH_TGT
         from UTIL_TARGET_LOADERS u
        where u.ORG_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)The join needs to be based on VEH_LOC and DAY in the form:
       ... WHERE u.ORG_ID = x.VEH_LOC
              AND x.DATE_INDEX between u.START_DATE and NVL(u.END_DATE,sysdate)I had one that worked just fine when only one entity was involved; the complication arises in that this is a division-level report so I have to individually resolve the subordinates and their goals before I can aggregate. This is one of two queries I need to tie together using a WITH clause so I can pivot the whole thing and present it in month-by-month fashion. When I try to tie it together like the query below, I get: invalid relational operator.
    select ttls.DATE_INDEX, SUM(ttls.LDS) as TTLLDS, SUM(ttls.TONS) as TTLTONS, u.TARGET_LTPH, u.TARGET_MTPH
      from UTIL_TARGET_LOADERS u,
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC) ttls
        where ttls.DATE_INDEX beween u.START_DATE and NVL(u.END_DATE,sysdate)
          and ttls.VEH_LOC = u.ORG_ID
      group by ttls.DATE_INDEXI know this is a nested mess, as it has to grab the production from two tables for a range of VEH_LOC values and sum and aggregate by day and VEH_LOC, then I have to try and match that to the targets based on VEH_LOC and day. My final query is to aggregate the whole mess of sums and averages by month.
    I'd appreciate it if someone can point me in the right direction.

    Figured it out.
    select ttl.DATE_INDEX, SUM(ttl.LDS) as TTLLDS, SUM(ttl.TONS) as TTLTONS,
         AVG((u.MACH_TPH_D+u.MACH_TPH_N)/2) as MTPH_TGT,
         AVG((u.LABOR_TPH_D+u.LABOR_TPH_N)/2) as LTPH_TGT
      from
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC) ttl, UTIL_TARGET_LOADERS u
      where u.ORG_ID = ttl.VEH_LOC
        and ttl.DATE_INDEX between u.START_DATE and NVL(U.END_DATE,sysdate)
      group by ttl.DATE_INDEX, (u.LABOR_TPH_D+u.LABOR_TPH_N)/2

  • Please can you help me in Tuning this query..?

    Hi ,
    Please can you help me in re-structuring this query? .Details are given below.
    I have 2 tables as shown below and data is like this.
    Position
    COD IND
    AAA N
    BBB N
    CCC N
    DDD Y
    Distance
    orig dest
    AAA BBB
    BBB CCC
    AAA CCC
    I need to create the records like this
    start end
    DDD AAA
    DDD BBB
    DDD CCC
    The query which i am using now for this is
    select p.code AS start,
    P1.CODE AS end
    from position p, position p1
    where
    P.CODE != P1.CODE
    AND (P.ind = 'Y' or P1.IND = 'Y')
    AND not exists
    (select 1
    from distance d
    where (d.orig = p.code or d.dest = p.code)
    and (d.orig = p1.code or d.dest = p1.code))
    table is having above a crore record. so its taking a lot of time.
    Please someone please help in tuning this query?
    Thanks and regards,
    Shabir

    Looks like you want this
    select a.strt, b.ends from
    (select p.code strt from position p where p.ind='Y') a,
    (select p.code ends from position p where p.ind='N') b
    where not exists (select 1 from distance d where d.orig=a.strt or d.dest=a.strt);
    DDD     AAA
    DDD     BBB
    DDD     CCCYour query result is:
    AAA     DDD
    BBB     DDD
    CCC     DDD
    DDD     AAA
    DDD     BBB
    DDD     CCCYou should be more descriptive about what kind of result you want, so that people can get more interested in helping you.

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

Maybe you are looking for

  • Video Capture: is this a good idea?  Also RAID 1 vs. 2 separate HDs

    Family videos on VHS. Original idea was to copy them all to DVD before the tapes degrade. Now thinking to capture the video on hard drives at the same time. This by taking video out of vhs/dvd combo unit (RCA connectors) into Canopus box, then via fi

  • Error message when printing from XP PC to Brother MFC-7420 over Express?

    My G4 worked without a Hitch but I cannot seem to get my XP PC to print over my Airport Express network on a Brother MFC-7420 laser multi-funcion printer. Has anyone been able to do this successfully?

  • How to connect my HP Officejet 4500 G510n-z to work wireless.

    I recently purchased the HP Officejet 4500 G510n-z, i have it connected to my netgear router which i can see that it is through netgear genie, but my computer will not connect. i have tried turning off my firewall, i have uninstalled and reinstalled

  • Call workflow from ABAP program

    created a zbusiness object (ZPRODH)with one key field product hierarchy, one attribute level number and one method display. I tested that zobject and using this object created workflow to display product hierarchy ,it is displaying it. now I have to

  • Base Value minus taxes

    Dear All I calculate a amount e.g base value - taxes base value of a condition 70 taxe                               5 Base value - taxes       70-5 =65 where i found that taxes are adding in base value instead substracting i want to use any general