Sql query executes faster 2. time despite clearing buffer cache/shared pool

Hi All,
I want to test query performance, so i clear cache in following way before each execution:
alter system flush buffer_cache;
alter system flush shared_pool;
But, first execution takes more time than second and consequent executions. For example first execution takes 30 seconds, consequent executions take 3 seconds.
Before each execution I clear the cache.
What can be the reason? I use TOAD for query execution. Does TOAD caches something after first execution?
And last question. Is there a dynamic query that query execution duration is stored?
Any help will be appreciated.
Thanks.

>
So there shouldn't be problem from the parameter, can you post result from V$SGA_DYNAMIC_COMPONENTS and v$SGAINFO ?
V$SGA_DYNAMIC_COMPONENTS
COMPONENT CURRENT_SIZE MIN_SIZE MAX_SIZE USER_SPECIFIED_SIZE OPER_COUNT LAST_OPER_TYP LAST_OPER LAST_OPER GRANULE_SIZE
shared pool 436207616 402653184 0 0 125 GROW IMMEDIATE 02-JUL-09 16777216
large pool 201326592 117440512 0 83886080 12 SHRINK DEFERRED 02-JUL-09 16777216
java pool 16777216 16777216 0 0 0 STATIC 16777216
streams pool 16777216 16777216 0 0 0 STATIC 16777216
DEFAULT buffer cache 1895825408 1711276032 0 16777216 137 GROW DEFERRED 02-JUL-09 16777216
KEEP buffer cache 0 0 0 0 0 STATIC 16777216
RECYCLE buffer cache 0 0 0 0 0 STATIC 16777216
DEFAULT 2K buffer cache 0 0 0 0 0 STATIC 16777216
DEFAULT 4K buffer cache 0 0 0 0 0 STATIC 16777216
DEFAULT 8K buffer cache 0 0 0 0 0 STATIC 16777216
DEFAULT 16K buffer cache 0 0 0 0 0 STATIC 16777216
DEFAULT 32K buffer cache 0 0 0 0 0 STATIC 16777216
ASM Buffer Cache 0 0 0 16777216 0 STATIC 16777216
V$SGA_INFO
NAME BYTES RESIZEABL
Fixed SGA Size 2086392 No
Redo Buffers 14688256 No
Buffer Cache Size 1895825408 Yes
Shared Pool Size 436207616 Yes
Large Pool Size 201326592 Yes
Java Pool Size 16777216 Yes
Streams Pool Size 16777216 Yes
Granule Size 16777216 No
Maximum SGA Size 2634022912 No
Startup overhead in Shared Pool 218103808 No
Free SGA Memory Available 50331648

Similar Messages

  • Query executes faster 2nd time

    Hi,
    So, the result% parameters are as follows, on a specific instance:
    AME                                                                                   TYPE VALUE
    result_cache_mode                                                                         2 MANUAL
    result_cache_max_size                                                                     6 20971520
    result_cache_max_result                                                                   3 5
    result_cache_remote_expiration                                                            3 0
    Executed in 0,156 secondsWell, if i run first time a large query, which takes much time (WITHOUT result_cache hint), this executes in 10 minutes. Then, some of my collegue said me second time i run the query i obtain the results faster than the first time, but i told him caching is not enabled, so why we got faster the results? The query execution plan is the same.
    So, are any buffers, or something, from which the database retrieves the results when executing again that query? Or any explanation why it executes faster on subsequent invocations?
    Thanks

    Roger22 wrote:
    So even if the result caching is not used, the data can be retrieved from the buffers.? okA fundamental concept for all databases and all modern file systems. A read-write memory cache that sits between the s/w and spinning rust.
    Also the basic reason why measuring performance for comparison using elapsed time is flawed - as the very SAME query with the SAME execution plan on the SAME data can show DIFFERENT elapsed times. Amount of I/O is constant, but the type of I/O (logical/fast versus physical/slow) is not.

  • SQL Query Executing longer time

    Hi , The below SQL query executing longer time . Please help to Improve the query performance. The query continuously running for more than 24 hours and failing with roolback segment error. Not getting the final output. Most of the tables are having milions of records.
    Select distinct
    IBS.ADSL_ACCESS_INFO,
    IBS.LIJ ,
    regexp_substr(OBVS.REFERENTIE_A,'[[:digit:]]+') as O_NUMBER,
    DBS.CKR_NUMMER_CONTRACTANT,
    DBS.DNUMBER
    FROM CD.IBS,
    CD.OIBL,
    CD.IH,
    CD.ODL,
    CD.OH,
    CD.DBS,
    CD.OBVS
    Where IBS.END_DT = To_Date('31129999', 'ddmmyyyy')
    AND OIBL.END_DT = to_date('31129999', 'ddmmyyyy')
    AND DBS.END_DT = to_date('31129999', 'ddmmyyyy')
    AND OBVS.END_DT = to_date('31129999', 'ddmmyyyy')
    AND OBVS.REFERENTIE_A LIKE 'OFM%'
    AND OIBL.INFRA_KEY = IH.INFRA_KEY
    AND OIBL.ORDERS_KEY = OH.ORDERS_KEY
    AND IBS.INFH_ID = IH.INFH_ID
    AND ODL.ORDH_ID = OH.ORDH_ID
    AND DBS.DEBH_ID = ODL.DEBH_ID
    AND OBVS.ORDH_ID = ODL.ORDH_ID
    Order By IBS.LIJ
    All the columns which are present in the where condition are having either Index/key (Primary/unique) except END_DT column.
    Please Advise

    Predicate pushing can help when it greatlly restricts the number of rows - you must experiment - might not work with all predicates pushed (as shown here)
    select distinct
           ibs.adsl_access_info,
           ibs.lij,
           obvs.o_number,
           dbs.ckr_nummer_contractant,
           dbs.dnumber
      from (select infh_id,adsl_access_info,lij
              from cd.ibs
             where end_dt = to_date('31129999','ddmmyyyy')
           ) ibs,
           (select infra_key,orders_key
              from cd.oibl
             where end_dt = to_date('31129999','ddmmyyyy')
           ) oibl,
           (select ordh_id,regexp_substr(obvs.referentie_a,'[[:digit:]]+') as o_number
              from cd.obvs
             where end_dt = to_date('31129999','ddmmyyyy')
               and referentie_a like 'OFM%'
           ) obvs,
           (select debh_id,ckr_nummer_contractant,dnumber
              from cd.dbs
             where end_dt = to_date('31129999','ddmmyyyy')
           ) dbs,
           cd.ih,
           cd.odl,
           cd.oh
    where oibl.infra_key = ih.infra_key
       and oibl.orders_key = oh.orders_key
       and ibs.infh_id = ih.infh_id
       and odl.ordh_id = oh.ordh_id
       and dbs.debh_id = odl.debh_id
       and obvs.ordh_id = odl.ordh_id
    order by ibs.lijRegards
    Etbin

  • Sql Query taking very long time to complete

    Hi All,
    DB:oracle 9i R2
    OS:sun solaris 8
    Below is the Sql Query taking very long time to complete
    Could any one help me out regarding this.
    SELECT MAX (md1.ID) ID, md1.request_id, md1.jlpp_transaction_id,
    md1.transaction_version
    FROM transaction_data_arc md1
    WHERE md1.transaction_name = :b2
    AND md1.transaction_type = 'REQUEST'
    AND md1.message_type_code = :b1
    AND NOT EXISTS (
    SELECT NULL
    FROM transaction_data_arc tdar2
    WHERE tdar2.request_id = md1.request_id
    AND tdar2.jlpp_transaction_id != md1.jlpp_transaction_id
    AND tdar2.ID > md1.ID)
    GROUP BY md1.request_id,
    md1.jlpp_transaction_id,
    md1.transaction_version
    Any alternate query to get the same results?
    kindly let me know if any one knows.
    regards,
    kk.
    Edited by: kk001 on Apr 27, 2011 11:23 AM

    Dear
    /* Formatted on 2011/04/27 08:32 (Formatter Plus v4.8.8) */
    SELECT   MAX (md1.ID) ID, md1.request_id, md1.jlpp_transaction_id,
             md1.transaction_version
        FROM transaction_data_arc md1
       WHERE md1.transaction_name = :b2
         AND md1.transaction_type = 'REQUEST'
         AND md1.message_type_code = :b1
         AND NOT EXISTS (
                SELECT NULL
                  FROM transaction_data_arc tdar2
                 WHERE tdar2.request_id = md1.request_id
                   AND tdar2.jlpp_transaction_id != md1.jlpp_transaction_id
                   AND tdar2.ID > md1.ID)
    GROUP BY md1.request_id
            ,md1.jlpp_transaction_id
            ,md1.transaction_versionCould you please post here :
    (a) the available indexes on transaction_data_arc table
    (b) the description of transaction_data_arc table
    (c) and the formatted explain plan you will get after executing the query and issuing:
    select * from table (dbms_xplan.display_cursor);Hope this helps
    Mohamed Houri

  • SQL query runs too many times in SQL server Profiler

    Hi Experts
    I have designed a report using SQL database.Report is based on Add Command Object, View and Table.Which are link and gives desired output.
    However it takes long time. In the SQL Sever profiler it shows that query is executing too many times.
    When in the Add Command object I edit the query Say I write TOP 5000 then it executes once however if I write Add 5001 then I face the same behavior.
    I have checked "Grouping on server" option in options.
    Please Advice.
    Regards
    Asha.

    Thanks Raghavendra for reply
    How adding group will help? I have to link this command objects with view and table.Also  When I add "TOP 5000" in add command query it executes only 1 time in SQL query Profiler hower if edit that query to "TOP 5001" then it again it executes several time which is impacting the performance.
    Please advice?
    Regards
    Asha.

  • Sql query is taking more time

    Hi all,
    db:oracle 9i
    I am facing below query prob.
    prob is that query is taking more time 45 min than earliar (10 sec).
    please any one suggest me .....
    SQL> SELECT MAX (tdar1.ID) ID, tdar1.request_id, tdar1.lolm_transaction_id,
    2 tdar1.transaction_version
    3 FROM transaction_data_arc tdar1
    4 WHERE tdar1.transaction_name ='O96U '
    5 AND tdar1.transaction_type = 'REQUEST'
    6 AND tdar1.message_type_code ='PCN'
    7 AND NOT EXISTS (
    8 SELECT NULL
    9 FROM transaction_data_arc tdar2
    10 WHERE tdar2.request_id = tdar1.request_id
    11 AND tdar2.lolm_transaction_id != tdar1.lolm_transaction_id
    12 AND tdar2.ID > tdar1.ID)
    13 GROUP BY tdar1.request_id,
    14 tdar1.lolm_transaction_id,
    15 tdar1.transaction_version;
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=17 Card=1 Bytes=42)
    1 0 SORT (GROUP BY) (Cost=12 Card=1 Bytes=42)
    2 1 FILTER
    3 2 TABLE ACCESS (BY INDEX ROWID) OF 'TRANSACTION_DATA_ARC
    ' (Cost=1 Card=1 Bytes=42)
    4 3 INDEX (RANGE SCAN) OF 'NK_TDAR_2' (NON-UNIQUE) (Cost
    =3 Card=1)
    5 2 TABLE ACCESS (BY INDEX ROWID) OF 'TRANSACTION_DATA_ARC
    ' (Cost=5 Card=918 Bytes=20196)
    6 5 INDEX (RANGE SCAN) OF 'NK_TDAR_7' (NON-UNIQUE) (Cost
    =8 Card=4760)

    prob is that query is taking more time 45 min than earliar (10 sec).Then something must have changed (data growth/stale statistics/...?).
    You should post as much details as possible, how and what it is described in the FAQ, see:
    *3. How to improve the performance of my query? / My query is running slow*.
    When your query takes too long...
    How to post a SQL statement tuning request
    SQL and PL/SQL FAQ
    Also, given your database version, using NOT IN instead of NOT EXISTS might make a difference (but they're not the same).
    See: SQL and PL/SQL FAQ

  • How do i get a output in CSV of a SQL query executed via SQL Command prompt

    Hi All,
    I have a question with reference to SQL command prompt. I have a sql query which runs properly and gives proper execution in SQL Management console in GUI.
    This report is used to pull the free disk space report of our servers
    As i want to schedule it as a report so i want to script it to run via SQL command prompt. I made the script and it works fine if i enter it in SQL command prompt. When i try to extract the output to a CSV File it fails. Below is the details of the command
    i am using to query to pull the data. Can anyone help me in getting the output of this query in SQL command prompt.
    sqlcmd -W -s , -S Servers FQDN
    use operationsmanager
    Go
    Query:"select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv"
    Go
    When i enter the command without the quotes when the query is starting and ending and also without the output command (-s "," -o "C:\DataSqlCmd.csv") it is working and shows the output in the command prompt. Below is the screen shot for
    your reference.
    Due to security reasons i have to erase the server names:
    But when i add the line to extract the output ( -s "," -o "C:\DataSqlCmd.csv") It gives me this error:
    The exact command would be:
    sqlcmd -W -s , -S CINMLVSCOM01.e2klab.ge.com
    use operationsmanager
    Go
    "select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv" -h-1
    Go
    saying the syntax is not correct or some thing as per the below screenshot.
    Can any one please help. Below is just the query whi i use to get the output in SQL management studio.
    Can any one make a command for the below quer so i can directly execute and test for getting the output.
    select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    Gautam.75801

    Can you try the below query?
    select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < 20 and CounterName like '% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    -- replace the below query part in the below SQLCMD C:\>SQLCMD -S SERVERNAME -E -d operationsmanager -Q "select * from sys.databases ds with (nolock) where name='master'" -s "," -o "F:\PowerSQL\MyData.csv" -h -1
    SQLCMD -S SERVERNAME -E -d OperationsManager -Q "select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "c:\MyData.csv" -h -1
    Refer for the other ways 
    http://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file
    --Prashanth

  • Oracle sql query execute in the apex

    hi:
    my requirement is, in region i have one text area item and query button.
    in this text area i am typing the any sql query and when i am pressing the query button it should display the query output report..
    pls give solution fast as soon as possible....
    Message was edited by:
    anbarasan

    Hi anbarasan,
    Maybe you can create a report of type "SQL query (PL/SQL Function returning query". Then in the region source, something like:
    DECLARE
    v_sql VARCHAR2 (4000);
    BEGIN
    v_sql := :PX_YOUR_ITEM;
    RETURN v_sql;
    END;
    Paulo Vale
    http://apex-notes.blogspot.com

  • Does SQL Query run faster with/without Conditions....

    Hi All, forgive my novice question.
    Was just wondering" In general if we run a SQL query on a single table; does my query run faster if there are multiple where conditions? or without. What happens if the conditions increase? My table is a big one with 5 million rows and some bitmap indexes defined on it.
    Thanks,
    Kon

    I think it's difficult to give general rule because there are too much dependencies on the fact that the columns are indexed or not, on the way tables and indexes statistics are computed or not, on the possible session or instance parameters that the optimizer may use, on the Oracle version, etc.
    Message was edited by:
    Pierre Forstmann

  • What is the process of oracle when SQL query execute

    hi
    I would like to know about process of oracle engine when we are execute a SQL query
    regards

    You can search that either in the Oracle docs or at fine blog http://antognini.ch/blog/ of Chris or in his book. You may also check SQL Tuning by Dan Tow for that matter.
    regards

  • How can i track the all sql/query executed from application

    How we can track all sql/query that has executed or being executing on oracle database server 10g r2.
    regards
    Prabhaker

    select s.sid,
           s.status,
           s.process,
           s.osuser,
           a.sql_text,
           p.program
    from v$session s,
         v$sqlarea a,
         v$process p
    where s.sql_hash_value = a.hash_value
      and s.sql_address    = a.address
      and s.paddr          = p.addr
      and s.schemaname     = '&1'
      and s.status         = 'ACTIVE'

  • Fiori Enhancment - BSP how to clear buffer/cache?

    Hi All,
    So I'm trying to make some enhancmenets to a Fiori app. I have downloaded it and reuploaded is as a new BSP application.
    I wanted to make some changes to the BSP, so I changed the code directly, in SAP.
    I thought I must be doing something wrong, but my changes weren't having any effect.
    To further test this I wrote some nonsense which should ahve broken it... but it still ran fine!
    To test further again I went to SICF and deactivated the node!! ANd it STILL worked fine!
    I opened new sessions in my browser, and new incognito windows, and closed it all and reopened it all, but it STILL works fine!
    There is clearly some kind of caching/buffering going on here, I've found the tables: O2PAGDIR and O2PAGDIRT have buffered values (found out this from ST02)
    But how do I clear it?! I turned buffering off in these tables, to see if that worked, and made another change, and tried to reload the table... but STILL the page loads with no changes.
    Please, can anyone tell me how to clear the buffer/cache that means that when I make UI chanegs in a BSP it doesn't show them?!
    Thank you
    Lindsay

    Hi Mauro,
    I overcame this issue in a variety of ways:
    Firstly, I do all the customisation of the BSP applications locally on my machine.
    Then I upload the whole BSP using the program /UI5/UI5_REPOSITORY_LOAD.
    In order to make sure the display you see in your browser is the up-to-date version, there are various cache clearing things you can do:
    Program /UI5/RESET_CACHEBUSTER - this has no UI, and takes only a second to run
    Transaction /UI5/THEME_TOOL : double click on "Invalidate Cache" to refresh the theme cache (if you have made theme changes)
    Then you have the two model caches mentioned above by Ashish - if you changes the Gateway service but aren't seeing these changes you should run these to ensure the model is up-to-date.
    Browser caches: make sure you browser cache is cleared: for Chrome this is easy: hit F12 (to get Dev toold open), clickk on the cog icon, and tick the box "Disable cache (while DevTootls is open)" - then keep devtools open while refreshing the page.
    The best way to enhance the BSP applications is locally on your machine, and do all your testing locally before uploading.
    I hope this helps, let me know how you get on.
    Lindsay

  • Sql query taking 2 much time to execute

    hi every body
    I am trying to JOIN two tables using the following criteria
    GL_JE_LINES.GL_SL_LINK_ID = CST_AE_LINES.GL_SL_LINK_ID
    but it takes too much time .. like (1 hr r more)
    which mens that something is wrong with my logic...
    any guidance will be appreciated ....
    thnx

    Hi,
    Do you run "Gather Schema Statistics" program on regular basis?
    What is the query you are trying to run?
    Please see the following threads.
    When your query takes too long ...
    When your query takes too long ...
    Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting
    Regards,
    Hussein

  • Query executation taking somuch time

    Hi
    I have created query on Inventory Cube(Copied from 0IC_C03).
    In cube maintainance i have changed the 'maintain non cumulative values' from calday and plant to only calday,
    because to get the correct data on day basis
    The query is based on material and vendor.
    it is taking so much time like 50 min to execute.
    I am thinking this is because of changing the 'maintain non cumulative values' in cube maintainance.
    But if i don't do that i can't get the correct values.
    Hope i explained the pbm very clearly.
    can anybody help me on this issue.
    I appreciate if anybody help me.
    Thanks
    Madhu

    HI,
    Have you tried other performance tuning activites, like creating aggregates, checked indices on the cube, etc.
    Also, did you give any filter criteria when running the query in the selection screens. If not do that as well.
    Suggest you run tcode ST03 in expert mode to check and see where the time is being taken and if needed run the query in debug mode using RSRT to see how best you can tune it further.
    Cheers,
    Kedar
    Cheers,
    Kedar

  • SQL Query to calculate on-time dispatch with a calendar table

    Hi Guys,
    I have a query (view) to calculate orders' fulfillment leadtimes.
    The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
    isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
    Please find below the current calculation for the On-Time Column:
    SELECT
    Week#
    , ClntGroup
    , CORD_DocumentCode
    , DESP_DocumentCode
    , Cord_Lines --#lines ordered
    , CORD_Qty --total units orderd
    , DESP_Lines --#lines dispatched
    , DESP_Qty --total units dispatched
    , Status
    , d_status
    , OpenDate --order open date
    , DateDue
    , DESP_PostedDate --order dispatched date
    , DocType
    , [Lead times1]
    , [Lead times2]
    , InFxO
    , OnTime
    , InFxO + OnTime AS InFullAndOneTime
    , SLADue
    FROM (
    SELECT
    DATEPART(WEEK, d.DateOpn) AS Week#
    , Clients.CustCateg
    , Clients.ClntGroup
    , d.DocumentCode AS CORD_DocumentCode
    , CDSPDocs.DocumentCode AS DESP_DocumentCode
    , COUNT(CORDLines.Qnty) AS Cord_Lines
    , SUM(CORDLines.Qnty) AS CORD_Qty
    , COUNT(CDSPLines.Qnty) AS DESP_Lines
    , SUM(CDSPLines.Qnty) AS DESP_Qty
    , CDSPLines.Status
    , d.Status AS d_status
    , d.OpenDate
    , d.DateDue
    , CDSPDocs.PostDate AS DESP_PostedDate
    , d.DocType
    , DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
    , DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
    , CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
    --On-Time by order according to Despatch SLAs
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
    THEN 1
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
    THEN 1
    WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
    AND d.DateDue >= CDSPDocs.PostDate
    THEN 1
    ELSE 0
    END AS OnTime
    --SLA Due (as a control)
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
    THEN DATEADD(DAY, 2 , d.OpenDate)
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
    AND CDSPDocs.PostDate IS NULL
    THEN DATEADD (DAY, 14 , d.OpenDate)
    ELSE CDSPDocs.PostDate
    END AS SLADue
    FROM dbo.Documents AS d
    INNER JOIN dbo.Clients
    ON d.ObjectID = dbo.Clients.ClntID
    AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
    LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
    ON d.DocID = CORDLines.DocID
    AND CORDLines.TrnType = 'L'
    LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
    ON CORDLines.TranID = CDSPLines.SourceID
    AND CDSPLines.TrnType = 'L'
    AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
    LEFT OUTER JOIN dbo.Documents AS CDSPDocs
    ON CDSPLines.DocID = CDSPDocs.DocID
    LEFT OUTER JOIN DimDate
    ON dimdate.[Date] = d.OpenDate
    WHERE
    d.DocType IN ('CASW', 'CORD', 'MORD')
    AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
    AND CORDLines.LneType IS NOT NULL
    AND d.DateDue <= CONVERT(date, GETDATE(), 101)
    GROUP BY
    d.DateOpn
    ,d.DocumentCode
    ,Clients.CustCateg
    ,CDSPDocs.DocumentCode
    ,d.Status
    ,d.DocType
    ,d.OpenDate
    ,d.DateReq
    ,CDSPDocs.PostDate
    ,CDSPLines.Status
    ,Clients.ClntGroup
    ,d.DocumentName
    ,d.DateDue
    ,d.DateOpn
    ) AS derived_table
    Please find below the DimDate table
    FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
    24/12/2014 NULL 0 1
    25/12/2014 Christmas Day 1 0
    26/12/2014 Boxing Day 1 0
    27/12/2014 NULL 0 0
    28/12/2014 NULL 0 0
    29/12/2014 NULL 0 1
    30/12/2014 NULL 0 1
    31/12/2014 NULL 0 1
    1/01/2015 New Year's Day 1 0
    2/01/2015 Day after New Year's 1 0
    3/01/2015 NULL 0 0
    4/01/2015 NULL 0 0
    5/01/2015 NULL 0 1
    6/01/2015 NULL 0 1
    This is what I get from the query:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 0
    52 Web Sales 123457 24/12/2014 30/12/2014 0
    52 Web Sales 123458 24/12/2014 29/12/2014 0
    52 Local Market 123459 24/12/2014 29/12/2014 0
    1 Web Sale 123460 31/12/2014 5/01/2015 0
    1 Local Market 123461 31/12/2014 6/01/2015 0
    As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 1
    52 Web Sales 123457 24/12/2014 30/12/2014 1
    52 Web Sales 123458 24/12/2014 29/12/2014 1
    52 Local Market 123459 24/12/2014 29/12/2014 1
    1 Web Sale 123460 31/12/2014 5/01/2015 1
    1 Local Market 123461 31/12/2014 6/01/2015 1
    I am using SQL Server 2012
    Thanks
    Eric

    >> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
    CREATE TABLE Calendar
    (cal__date date NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
     FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal__date = '2007-04-05',
     AND C2.cal__date = '2007-04-10'; 
    We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
    The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
    The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
    look stupid in 2015. 
    You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
    You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
    like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
    We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Please find below the current calculation for the On-Time Column: <<
    “No matter how far you have gone down the wrong road, turn around”
     -- Turkish proverb
    Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
    ONE statement than I have seen in entire major corporation databases.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

Maybe you are looking for

  • How can I boot my PXI controller into real-time without a floppy disk?

    My PXI controller is in a lab which has intense magnetic fields that could corrupt the floppy disk used to boot the PXI controller into the LabVIEW Real-Time (RT) Operating System. How can I boot the PXI controller into real-time directly from the ha

  • How to uninstall a Greasemonkey userscript in Firefox 3.6.16? Manage User Scripts box doesn't appear as before.

    I need to uninstall an old userscript installed through Greasemonkey. Usually I go via Tools-->Greasemonkey-->Manage User Scripts or right-click on the monkey icon on the bottom left and choose Manage User Scripts and get this large window where I ca

  • Deffer Payment Terms

    Hi Happy new year to ever one Can any one suggest me the below we required different Payment Terms line item wise In Sales order for different materials we need different payment terms Does it possible? Regd Sudha

  • Generating a data channel in Diadem 6.0

    I would like to generate a data channel to represent a x/y curve. e.g.: x: 0.1/0.2/0.3/0.5/0.9 y: 1/3/10/11.5/15 How can i do this and how can i use these datas in different autosequences? The next question is: how can i control with these datas an a

  • Ethernet does not show up in list of interfaces

    Hello, we have a customer with an iMac and they are having issues with the wired connection on it.  Occasionally, it will just say "disconnected" when they go to system preferences, network. I had her remove the connection but when she goes to readd