Query to calculate business days

i have table name order table . in that i have column name install date,order date.
the difference bet ween order date and install date should be greate than or equal to 3 working days.
fri and sat are holidays.
i need one query to find the difference betwwen orderdate and install date is greate than 3 working days

You can try like this
SQL> with order_tbl
  2  as
  3  (
  4    select to_date('01-jan-2013', 'dd-mon-yyyy') order_date
  5         , to_date('05-jan-2013', 'dd-mon-yyyy') installed_date
  6      from dual
  7    union all
  8    select to_date('04-jan-2013', 'dd-mon-yyyy') order_date
  9         , to_date('07-jan-2013', 'dd-mon-yyyy') installed_date
10      from dual
11    union all
12    select to_date('06-jan-2013', 'dd-mon-yyyy') order_date
13         , to_date('15-jan-2013', 'dd-mon-yyyy') installed_date
14      from dual
15    union all
16    select to_date('19-jan-2013', 'dd-mon-yyyy') order_date
17         , to_date('25-jan-2013', 'dd-mon-yyyy') installed_date
18      from dual
19    union all
20    select to_date('25-jan-2013', 'dd-mon-yyyy') order_date
21         , to_date('30-jan-2013', 'dd-mon-yyyy') installed_date
22      from dual
23  )
24  select order_date, installed_date, count(date_list) date_count
25    from (
26            select t.*, t.order_date + (level-1) date_list
27              from order_tbl t
28            connect by level <= installed_date - order_date + 1
29               and prior order_date = order_date
30               and prior sys_guid() is not null
31         )
32   where to_char(date_list, 'fmday') not in ('saturday', 'sunday')
33   group
34      by order_date, installed_date
35  /
ORDER_DAT INSTALLED DATE_COUNT
19-JAN-13 25-JAN-13          5
25-JAN-13 30-JAN-13          4
04-JAN-13 07-JAN-13          2
01-JAN-13 05-JAN-13          4
06-JAN-13 15-JAN-13          7
SQL> In the above code i have used the WITH clause to generate sample data. you can just use the SELECT query alone.

Similar Messages

  • Fucntion to Calculate business days (exclude weekends & holidays) between two days

    Hello,
    I need to be able to calculate business days between two dates excluding weekends and holidays. I do have a date dimension and also flags which denote weekday, holiday. Would really appreciate help in building a udf for the business days calculation.
    Thanks,

    Hi, Please take a look and tweak accordingly. Best of luck.
    --Assuming data dimension table something like the following
    --tblDateDim (DT date primary key,
    flagHoliday bit,
    flagWeekday bit
    CREATE FUNCTION fnBusinessDays (
    @StartDate DATE,
    @EndDate DATE
    RETURNS INT
    AS
    BEGIN
    DECLARE @Days INT ;
    SELECT @Days = count(*)
    FROM tblDateDim --// date dimension
    WHERE
    ( DT BETWEEN @StartDate AND @EndDate) --// dt is date column in the table.
    AND --// also flags which denote weekday, holiday
    flagHoliday = 0 --// flagHoliday= 1--Holiday;= 0 --workingday/businessday
    AND
    flagWeekday = 1 --// FlagWeekday = 1--businessday ; =0 --weekend (Saturday and Sunday)
    RETURN (@Days)
    END
    GO

  • Calculate "Business Days" and account for holidays

    I have played with Date math based on what I have found for documentation, and adding an arbitrary number of days is pretty easy. But what about adding an arbitrary number of business days? I found a web site that talks about "Next business day",
    which could be adapted I am sure, but it only accounts for weekends. I want to calculate the date an arbitrary number of business days from a provided date. So, +3 business days calculated from a Monday should produce the date of the following Thursday,
    and calculated from a Friday should produce the date of the next Wednesday. And calculated from Friday Sept 4, 2015 (Friday before Labor Day) should produce Thursday Sept 10, 2015.
    Given that Windows is very business focused, I wonder if there is some nice hidden .NET functionality to calculate business days based on holidays as well? I know, some offices might give extra days off, four day weekends, etc. But those would be edge case
    enough to be safely ignorable for my purposes. Indeed, even holidays could probably be ignored, but if there is a quick approach I would rather use it. If I would need to code some sort of Exchange calendar scraper or some such, I'll live with just accounting
    for weekends. ;)

    You can pull holiday info from outlook.hol file and do the date math based on it. It won't be 100% reliable though. Not all the holidays listed in calendar are non-business days (not in all countries at least). International support may also present additional
    issues: in some countries it is a common practice to "move" weekend days to fill a single day gap between holidays and weekend (which screws up next business day calc anyway, regardless of holiday info :-). Not to mention all the possible industry-wide
    or company specific policies regarding working days.
    Gleb.

  • Calculate Business day

    Hi,
    Iam working on a logic to calculate the posting date in XI. I have used graphical mapping in the scenario.
    The logic is to claculate the 3rd business date of the month. You need to look at the calendar and exclude Saturdays, Sundays and Holidays.
    For example if we take February 2008 the 3rd business day is 5th Feb 08 as 02/Feb and 03/Feb are saturday and sundays.
    If monday(04/Feb) was a holiday then the 3rd business day will be 6th Feb.
    Can you give this logic in XI graphical mapping.
    Best Regards
    Suresh

    Hi Ram,
    Thanks for the immediate reply. The XI scenario is File to IDOC. But the scenario is already developed using graphical mapping and I just need to change the posting date logic in it. I believe the holidays are maintained in SAP tables. Is there a way to get the holidays list from SAP using User defined functions in XI.
    Best Regards
    Suresh

  • Calculate business day between two dates

    Hi Guys
    I need the count of business days between two  dates
    Date1, Date2 i need the count only business day (exclude sartuday&sunday)
    If date1 is null or nothing i need to pass 0
    If date2 is null or nothing i need to pass 0
    help on this

    Hi,
    To achive this within SSRS, go to the report code window and add the below
    Function getBusinessDaysCount(ByVal tFrom As Date, ByVal tTo As Date) As Integer
    Dim tCount As Integer
    Dim tProcessDate As Date = tFrom
    For x as Integer= 1 To DateDiff(DateInterval.Day, tFrom, tTo) + 1
    If Not (tProcessDate.DayOfWeek = DayOfWeek.Saturday Or tProcessDate.DayOfWeek = DayOfWeek.Sunday) Then
    tCount = tCount + 1
    End If
    tProcessDate = DateAdd(DateInterval.Day, 1, tProcessDate)
    Next
    Return tCount
    End Function
    In the textbox where you need to display the value, add the below expression
    =Code.getBusinessDaysCount(parameters!StartDate.Value,parameters!EndDate.Value)
    It is assumed the you want to pass the two days from parameters named Startdate and EndDate. If not, modify the expression with required values.
    Regards
    Please click "Mark as Answer" if this resolves your problem or "Vote as Helpful" if you find it helpful. BH

  • Previous business day in sql query

    Hi,
    Is there a way to calculate the previous business day on teh sql query without using a function call.
    Typically in the query where clause as seen below:
    eg)
    select * from sales where sale_date ='+previous_buss_day+'
    If so please let me know....Thnx in advanc.

    that depends if your organization has a defined set of business days that will includes non-working days (holidays, etc.). if there is you need to have a lookup table that has a listing of all available normal business day and non-working days. then match it up with your transaction table. otherwise you can use the current system date less 1 days.
    e.g.
    select * from sales where sale_date = trunc(sysdate-1)

  • Calculate number of Business Days

    I need to calculate number of Business Days in BODS. Lets say I have One source table and One Date Dimension table to identify Business Day and need to calculate the no of working days and load in to FACT table (Like in screenshot below)?
    By adding Query transform, I can calculate no of Days, but how to calculate working days between ORDER_RECEIVED_DATE and ORDER_SHIPPED_DATE.
    SQL: select count(*) from DIM_DATE  where DATE between ORDER_RECEIVED_DATE and ORDER_SHIPPED_DATE and HOLIDAY_FLAG='NO'

    Prashanth Chinta,
    I have simulated this Job in my repository and and below are the steps by step implementation.
    Your Dataflow will look like below. It contains the source and Target table with expected results. Hope this is what you are looking for.
    DIM_DATE table contains all the dates in a year and mark each date either Holiday as 'YES' or 'NO'
    Qry_Total_Ship_Days Query Transform
    Qry_Join Query Transform
    Qry_Filter_Holidays Query Transform
    Qry_Cnt_Holidays Query Transform
    Qry_Cnt_Holidays Query Transform (This is to show the groupby columns)
    Qry_Cal_Ship_Days Query Transform

  • Calculate: SYSDATE + TWO BUSINESS DAYS

    Is there a simple way (function) in 10g to calculate
    - "SYSDATE + TWO BUSINESS DAYS (not including Saturday)"
    - "SYSDATE + TWO BUSINESS DAYS (including Saturday)"
    in SQL ? Or I have to write a function to calculate manually?
    Thank you for any idea.

    One possible solution, based on a table of holidays:
    CREATE TABLE HOLIDAY_TABLE
    (HOLIDAY_DATE DATE PRIMARY KEY,
    DESCRIPTION VARCHAR2(50));
    SELECT dt
      FROM (SELECT dt, RANK () OVER (ORDER BY dt) pos
              FROM (SELECT     TRUNC (SYSDATE) + LEVEL dt,
                               CASE
                                  WHEN TRIM (TO_CHAR (SYSDATE + LEVEL, 'DAY')) = 'SATURDAY'
                                   OR TRIM (TO_CHAR (SYSDATE + LEVEL, 'DAY')) = 'SUNDAY'
                                  THEN 0
                                  ELSE 1
                               END cnt
                          FROM DUAL
                    CONNECT BY LEVEL < 7)      -- number large enough to generate a complete list of possible days
             WHERE cnt = 1 AND (SELECT COUNT (*)
                                  FROM holiday_table
                                 WHERE holiday_date = dt) = 0)
    WHERE pos = 2  -- number of working days to add Miguel

  • How to calculate previous business day

    Hi,
    I'm stuck with an issue.
    Task is to calculate 1 to 6 previous business days with reference to system date.
    Conditions are : Week is 6 day. In first case its Sunday as weekend holiday and in second case its Saturday as weekend holiday.
    Another condition is I have to take care of bank holidays also which are stored in a separate table in database.
    How to implement this logic ?
    Below I have implemented some logic but its not running correctly for some dates adjusted according to bank holidays.
    In this code I'm taking Sunday as weekend off and To_Date is having the list of bank holidays for 2012.
    SELECT
      CASE
        WHEN TRUNC(SYSDATE-1) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
        THEN (
          CASE
            WHEN TRUNC(SYSDATE-2) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
            Then (
            CASE
            WHEN TRUNC(SYSDATE-3) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
            Then (
            CASE
            WHEN TRUNC(SYSDATE-4) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
            Then (       
            CASE
            WHEN TRUNC(SYSDATE-5) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
            Then (       
            CASE
            WHEN TRUNC(SYSDATE-6) IN (TO_DATE('01-JAN-2012'), TO_DATE('02-JAN-2012'), TO_DATE('07-APR-2012'), TO_DATE('09-APR-2012'), TO_DATE('07-MAY-2012'), TO_DATE('04-JUN-2012'), TO_DATE('05-JUN-2012'), TO_DATE('27-AUG-2012'), TO_DATE('25-DEC-2012'), TO_DATE('26-DEC-2012'))
            THEN DECODE(TO_CHAR((SYSDATE-6),'DAY'),'MONDAY   ',TRUNC((SYSDATE-6)-7),'TUESDAY  ',TRUNC((SYSDATE-6) - 7),'WEDNESDAY',TRUNC((SYSDATE-6) - 7),'THURSDAY ',TRUNC((SYSDATE-6) - 7),'FRIDAY   ',TRUNC((SYSDATE-6) - 7),'SATURDAY ',TRUNC((SYSDATE-6) - 7),'SUNDAY   ',TRUNC((SYSDATE-6) - 6))
            ELSE DECODE(TO_CHAR((SYSDATE-5),'DAY'),'MONDAY   ',TRUNC((SYSDATE-5)-7),'TUESDAY  ',TRUNC((SYSDATE-5) - 7),'WEDNESDAY',TRUNC((SYSDATE-5) - 7),'THURSDAY ',TRUNC((SYSDATE-5) - 7),'FRIDAY   ',TRUNC((SYSDATE-5) - 7),'SATURDAY ',TRUNC((SYSDATE-5) - 7),'SUNDAY   ',TRUNC((SYSDATE-5) - 6))
            END)
            ELSE DECODE(TO_CHAR((SYSDATE-4),'DAY'),'MONDAY   ',TRUNC((SYSDATE-4)-7),'TUESDAY  ',TRUNC((SYSDATE-4) - 7),'WEDNESDAY',TRUNC((SYSDATE-4) - 7),'THURSDAY ',TRUNC((SYSDATE-4) - 7),'FRIDAY   ',TRUNC((SYSDATE-4) - 7),'SATURDAY ',TRUNC((SYSDATE-4) - 7),'SUNDAY   ',TRUNC((SYSDATE-4) - 6))
            END)
            ELSE DECODE(TO_CHAR((SYSDATE-3),'DAY'),'MONDAY   ',TRUNC((SYSDATE-3)-7),'TUESDAY  ',TRUNC((SYSDATE-3) - 7),'WEDNESDAY',TRUNC((SYSDATE-3) - 7),'THURSDAY ',TRUNC((SYSDATE-3) - 7),'FRIDAY   ',TRUNC((SYSDATE-3) - 7),'SATURDAY ',TRUNC((SYSDATE-3) - 7),'SUNDAY   ',TRUNC((SYSDATE-3) - 6))
            END)
            ELSE DECODE(TO_CHAR((SYSDATE-2),'DAY'),'MONDAY   ',TRUNC((SYSDATE-2)-7),'TUESDAY  ',TRUNC((SYSDATE-2) - 7),'WEDNESDAY',TRUNC((SYSDATE-2) - 7),'THURSDAY ',TRUNC((SYSDATE-2) - 7),'FRIDAY   ',TRUNC((SYSDATE-2) - 7),'SATURDAY ',TRUNC((SYSDATE-2) - 7),'SUNDAY   ',TRUNC((SYSDATE-2) - 6))
          END )
              ELSE DECODE(TO_CHAR((SYSDATE-1),'DAY'),'MONDAY   ',TRUNC((SYSDATE-1)-7),'TUESDAY  ',TRUNC((SYSDATE-1) - 7),'WEDNESDAY',TRUNC((SYSDATE-1) - 7),'THURSDAY ',TRUNC((SYSDATE-1) - 7),'FRIDAY   ',TRUNC((SYSDATE-1) - 7),'SATURDAY ',TRUNC((SYSDATE-1) - 7),'SUNDAY   ',TRUNC((SYSDATE-1) - 6))
          END)
        ELSE DECODE(TO_CHAR((SYSDATE),'DAY'),'MONDAY   ',TRUNC((SYSDATE)-7),'TUESDAY  ',TRUNC((SYSDATE) - 7),'WEDNESDAY',TRUNC((SYSDATE) - 7),'THURSDAY ',TRUNC((SYSDATE) - 7),'FRIDAY   ',TRUNC((SYSDATE) - 7),'SATURDAY ',TRUNC((SYSDATE) - 7),'SUNDAY   ',TRUNC((SYSDATE) - 6))
      END
    FROM DUAL;Edited by: user9082359 on Oct 21, 2012 8:55 PM

    Hello,
    There are two business streams.
    For one stream,Saturday is holiday and for other Sunday is holiday and
    ('01-JAN-2012'), ('02-JAN-2012'), ('07-APR-2012'), ('09-APR-2012'), ('07-MAY-2012'), ('04-JUN-2012'), ('05-JUN-2012'), ('27-AUG-2012'), ('25-DEC-2012'), ('26-DEC-2012') is my list of bank holidays for 2012 year.
    Now if suppose we have to calculate 1 previous business day for today 22 Oct,it would be 20 Oct for one stream and 21 Oct for another stream.
    Like this I have to calculate 1-6 previous business days for sysdate.
    Now If there is a bank holiday coming in between e.g. suppose 20 Oct is a bank holiday and Sunday is weekend holiday,so now 1 previous business day would be 19 Oct.
    I hope I have made myself clear.
    Thanks and waiting for solution of this issue.

  • Formula to calculate due date considering only business days (Middle East)

    I have a form which contains two fields: 'Start Date' and 'Completion Date'; the 'Completion Date' field is automatically set, it's always 3 more days than the 'Start Date' field.
    The problem is that these 3 days must be only business days.
     - if 'Start Date' is on Sunday then the 'Completion Date' should be set to next Wednesday
     - if 'Start Date' is on Monday then the 'Completion Date' should be set to next Friday
     - if 'Start Date' is on Tuesday then the 'Completion Date' should be set to next Sunday
     - if 'Start Date' is on Wednesday then the 'Completion Date' should be set to next Monday
     - if 'Start Date' is on Thursday then the 'Completion Date' should be set to next Tuesday
     - if 'Start Date' is on Friday then the 'Completion Date' should be set to next Tuesday
     - if 'Start Date' is on Saturday then the 'Completion Date' should be set to next Tuesday
    Friday and Saturday should be ignored as 'Completion Date' (weekend in Middle East).
    Anyone has any idea of how to make this formula? I need to put it into a calculated SharePoint column.
    Thanks in advance for your help.

    Hi
    check my post
    http://www.romeodonca.ro/Lists/DB_IT/Adding%20a%20number%20of%20working%20days%20to%20a%20specific%20date
    If you need more details let me know
    Romeo Donca, Orange Romania (MCSE, MCITP, CCNA) Please Mark As Answer if my post solves your problem or Vote As Helpful if the post has been helpful for you.

  • Formula to calculate due date considering only business days

    Hello,
    I have a form which contains two fields: 'Start Date' and 'Due Date'.  The 'Due Date' field is automatically set , it's always 4 more days than the 'Start Date' field. 
    The problem is: Those 4 days must be only business days... e.g., if 'Start Date' is on Friday then the 'Due Date' should be set on the next Thursday. Saturday and Sunday are ignored. Anyone has any idea of how to make this formula? I need to put it into
    a calculated SharePoint column.
    Thanks in advance.

    Hello,
    you can use this calculated formula for Due Date:
    =IF(WEEKDAY(StartDate+4)=7,StartDate+6,IF(WEEKDAY(StartDate+4)=1,StartDate+5,StartDate+4))
    Be aware that it treats holidays and national bank holidays as business days unless they are on a weekend. 
    cheers, teylyn
    teylyn,
    Thank you for your example. However this formula doesn't seem to be entirely correct, right? Because
    according to the excel spreadsheet you sent, when the Start Date is May 29th (Thursday), Due Date
    will be on June 2nd (Monday) taking so only two days rather than four.
    Maybe a little change in this formula and we will be fine.

  • 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

  • Oracle 8i: Business Days Calculation in a Subquery

    To Whom It May Concern:
    I apologize if this has been posted already, but I didn't find any threads that address my issue:
    I need to find the number of business days between 2 dates (excludes weekends) provided by dates from an outer query such as the following:
    SELECT
         C.CUSTOMER_ID
         , C.ENTRY_DATE
         , C.COMPLETION_DATE
         , <SOME SUBQUERY HERE THAT CALCULATES THE NUMBER OF BUSINESS DAYS BETWEEN C.COMPLETION_DATE AND C.ENTRY_DATE> AS BUSINESS_DAYS
    FROM CUST_TABLE C
    Thanks for your time and advice.
    Max

    you don't need a subquery. it's a very simple formula
    Re: query regarding dates
    (you may need to change the case to a decode for v8 - I don't remember when it was introduced)

  • Calculation of Business day in OBIEE

    Hi,
    How to calculate the business day in OBIEE by excluding both weekends and public holidays.
    Please guide me

    If you want the "nth business day," here is something I prepared.
    Understanding the Concept in Layman Terms
    The first step to deriving the calculation is looking at a calendar. For our example, we will calculate the 6th business day of each month.
    1) Observation One: When the first day of the month is Saturday, the 6th business day occurs when “today’s date minus the first-day-of-the month equals 9.”
    2) Observation Two: When the first day of the month is Sunday, the 6th business day occurs when the above calculation equals 8.
    3) Observation Three: When the first day of the month is Monday – Friday, the 6th business day occurs when the above calculation equals 7.
    Building the SQL
    Below are the SQL statements that correspond to the above observations:
    4) When the first day of the month is Saturday…
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) = 6 AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = 9
    5) When the first day of the month is Sunday…
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) = 7 AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = 8
    6) When the first day of the month is Monday – Friday…
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) NOT IN (6,7) AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = 7
    Putting the SQL Statements Together
    When any of the above conditions are true (“OR” between each condition), then (THEN) “today” is the 6TH business day; otherwise (ELSE) it is not the 6th business day. Below is the final SQL:
    CASE WHEN
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) = 6 AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = *9*
    OR
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) = 7 AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = *8*
    OR
    DAYOFWEEK(TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE)) IN (1,2,3,4,5) AND DAYOFMONTH(CURRENT_DATE)-DAYOFMONTH(TIMESTAMPADD(SQL_TSI_DAY,1,TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(CURRENT_DATE)*-1,CURRENT_DATE))) = *7*
    THEN '6th Business Day' ELSE 'Not 6th Business Day' END
    Modifying the Query for the nth Business Day
    To modify the above SQL for the nth business day, change the numbers in bold to the appropriate values.

  • Service Requests-Business days when year changes

    Hi All,
    I am trying to calculate for how long a SR has been open in business days only.
    I have successfully used Mike Lairson's formula for the last 9 months but it seems it cannot cope with year changes. If the begin data is in 2009 and the end date in 2010, the results are not correct anymore.
    E.G. For an SR that was opened on 12/30/2009 and closed on 01/05/2010 should return 5 business days but it is actually returning 110.
    The syntax that I used so far is:
    (CASE
    /* Convert Sunday to the Business Day Of the Year */
    WHEN DAYOFWEEK("Service Request"."Closed Date and Time") = 1
    THEN (DAYOFYEAR("Service Request"."Closed Date and Time") - WEEK("Service Request"."Closed Date and Time")) -
    (WEEK("Service Request"."Closed Date and Time") - 2)
    /* Convert Saturday to the Business Day Of the Year */
    WHEN DAYOFWEEK("Service Request"."Closed Date and Time") = 7
    THEN (DAYOFYEAR("Service Request"."Closed Date and Time") - WEEK("Service Request"."Closed Date and Time")) -
    (WEEK("Service Request"."Closed Date and Time") - 1)
    /* Convert Mon-Fri to the Business Day Of the Year */
    ELSE (DAYOFYEAR("Service Request"."Closed Date and Time") -
    WEEK("Service Request"."Closed Date and Time")) +
    (2 - WEEK("Service Request"."Closed Date and Time")) END)
    (CASE
    /* Convert Sunday to the Business Day Of the Year */
    WHEN DAYOFWEEK("Service Request"."Opened Date") = 1
    THEN (DAYOFYEAR("Service Request"."Opened Date") -
    WEEK("Service Request"."Opened Date")) -
    (WEEK("Service Request"."Opened Date") - 2)
    /* Convert Saturday to the Business Day Of the Year */
    WHEN DAYOFWEEK("Service Request"."Opened Date") = 7
    THEN (DAYOFYEAR("Service Request"."Opened Date") -
    WEEK("Service Request"."Opened Date")) -
    (WEEK("Service Request"."Opened Date") - 1)
    /* Convert Mon-Fri to the Business Day Of the Year */
    ELSE (DAYOFYEAR("Service Request"."Opened Date") -
    WEEK("Service Request"."Opened Date")) +
    (2 - WEEK("Service Request"."Opened Date"))
    END)
    +
    /* Adjust for Year Change */
    (365 * (YEAR("Service Request"."Closed Date and Time") -
    YEAR("Service Request"."Opened Date")))
    Any ideea or hint would be highly appreciated.
    Thank you.
    Regards,
    Dorin
    Edited by: user805960 on 06.01.2010 07:07

    Hi,
    i used this formula to find out the days it calculates between 31/12/2009 and 01/01/2010, the result it gave was 106 days.
    So i subtracted 106 from 365 days (365-106=259)in the formula, the formula is now giving the correct values.
    I think we have to add the total working days and not the no.of days in a year.
    Please can you all reconfirm the results.
    Thanks
    Neena
    Edited by: NNK on Jan 11, 2010 3:16 PM

Maybe you are looking for