DateDiff to show working days

Hello
I have set up a calculated field in a report to show the number of days between a job start and end date. I am using T-SQL:
=DateDiff("D", fields!jobstartdate.value, fields!jobenddate.value)
This works fine, but is of course including weekends in its calculation. Is there a way, using datediff, I can include working days only?
Any insight appreciated - thanks.

with tmp(plant_date,d) as
   select cast('20150201' as datetime),datename(weekday,cast('20150201' as datetime))
   union all
   select plant_date + 1,datename(weekday,plant_date+1)
     from tmp
    where plant_date < '20150228'
select* into calendar
  from  tmp
option (maxrecursion 0)
create table #t (dt_from date, dt_to date)
insert into #t values ('20150201','20150209') ---6 working days
insert into #t values ('20150202','20150205') ---4 working day
-- Compute weekday; assume Monday as the first day of week
SELECT dt_from,dt_to,count(plant_date)
FROM #t join calendar on plant_date between dt_from and dt_to
where d not in ('Saturday','Sunday')
group by dt_from,dt_to
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Show Working days transaction on Weekends and Holidays

    Hi,
    I have an objective to show last working days transaction (consider Friday) on Saturday and Sunday, also
    if the next day is also a Holiday then i have to post previous days transactions on Holiday too.
    Example:I need to show Friday Sep 1,2006 Transactions on
    Sep 2,2006
    Sept 3,2006
    Sep 4,2006 (Labor Day -- Holdiay)
    Restriction:PL/SQL not allowed( i know it is hard to believe ..sorry)
    Here is the Query that i have written which takes care of Sat and Sundays.I am having problem with Posting the data on Holidays.
    -- This Query selects all working days only
    select TRADE_DATE,
    Case when PORT_ID = 'FFSEX5' then SUM(PRINCIPAL) End as FFSDirect,
    Case when PORT_ID = 'FFSEX5' then trunc(AVG(RATE),2) End as FFSDirect_Avg,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then SUM(PRINCIPAL) End as FFSBroker,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then trunc(AVG(RATE),2) End as FFSBroker_Avg,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then SUM(PRINCIPAL) End as Euro3,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then trunc(AVG(RATE),2) End as Euro3_Avg,0 AS FLAG
    FROM CV_TRADE_HIST
    Group by port_id,Trade_date
    Union
    -- Accumulates Saturdays
    select (TRADE_DATE+1) as Trade_Date,
    Case when PORT_ID = 'FFSEX5' then SUM(PRINCIPAL) End as FFSDirect,
    Case when PORT_ID = 'FFSEX5' then trunc(AVG(RATE),2) End as FFSDirect_Avg,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then SUM(PRINCIPAL) End as FFSBroker,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then trunc(AVG(RATE),2) End as FFSBroker_Avg,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then SUM(PRINCIPAL) End as Euro3,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then trunc(AVG(RATE),2) End as Euro3_Avg,0 AS FLAG
    FROM CV_TRADE_HIST Where to_char(trade_date,'dy')='fri'
    Group by port_id,Trade_date
    Union
    -- Accumulates Sundays
    select (TRADE_DATE+2) as Trade_Date,
    Case when PORT_ID = 'FFSEX5' then SUM(PRINCIPAL) End as FFSDirect,
    Case when PORT_ID = 'FFSEX5' then trunc(AVG(RATE),2) End as FFSDirect_Avg,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then SUM(PRINCIPAL) End as FFSBroker,
    Case when PORT_ID in ('FFSEX3', 'FFSEX2', 'CLS') then trunc(AVG(RATE),2) End as FFSBroker_Avg,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then SUM(PRINCIPAL) End as Euro3,
    Case when PORT_ID in ('EPIEX3', 'ACK', 'ETCEX3', 'CKD') then trunc(AVG(RATE),2) End as Euro3_Avg,0 AS FLAG
    FROM CV_TRADE_HIST Where to_char(trade_date,'dy')='fri'
    Group by port_id,Trade_date
    UNION
    -- TO ADD HOLIDAYS TO THE RECORD SET
    SELECT HOLI_DT AS TRADE_DATE,
    0 AS FFSDirect,
    0 AS FFSDirect_Avg,
    0 AS FFSBroker,
    0 AS FFSBroker_Avg,
    0 as Euro3,
    0 AS Euro3_Avg,
    0 AS Euro4,
    1 AS FLAG
    FROM V_INTR_SRC_HOLIDAY
    WHERE TO_NUMBER(TO_CHAR(HOLI_DT,'YYYY'))=2006 and TO_CHAR(HOLI_DT,'DY') NOT IN ('SAT','SUN')
    ORDER BY 1 DESC
    Logic i was trying (I NEED TO POST THE PREVIOUS DAYS TRANSACTIONS WHERE FLAG=1 WHICH IS A HOLIDAY.using Lag())
    ****My constraint is no PL/SQL and no DML is allowed.
    Please let me know is there anyway i can achieve this.I tried using Lag(), it did not work for me,Any suggestions?
    Thank you,
    Jay Brahmanapalli
    Message was edited by:
    user530625

    Here's a simple version:
    Setup:
    drop table trade_history
    create table trade_history
    ( trade_date date not null
    , amount number not null
    , ticker varchar2(6) not null
    declare
        tdate date;
        tamount number;
    begin
        tdate := trunc(sysdate);
        for i in 1..365 loop
            tdate := tdate - 1;
            tamount := 200 - i;
            insert into trade_history (trade_date, amount, ticker)
            values (tdate, tamount, 'ORCL');
        end loop;
    end;
    commit
    drop table holidays
    create table holidays
    ( holiday_date date not null
    , previous_business_date date not null
    , holiday_name varchar2(240)
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('25-DEC-05','24-DEC-05','Christmas Day')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('26-DEC-05','24-DEC-05','Boxing Day')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('06-SEP-06','05-SEP-06','A midweek example')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('04-SEP-06','01-SEP-06','A Monday example')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('07-AUG-06','04-AUG-06','A two day post w/e example')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('08-AUG-06','04-AUG-06','A two day post w/e example')
    insert into holidays (holiday_date, previous_business_date, holiday_name)
    values ('26-DEC-06','24-DEC-06','Boxing Day 2006')
    commit
    /And a very simple example query
    select last_business_day, ticker, sum(amount), count(amount)
    from (
    select nvl(hol.previous_business_date, trade_date)
           - case to_char(nvl(hol.previous_business_date, trade_date),'D')
                        when '7' then 2
                        when '6' then 1
                        else 0
                        end last_business_day
         , ticker, amount
    from   trade_history th
    left join holidays hol on hol.holiday_date = th.trade_date
    group by last_weekday, ticker
    order by 1,2You should be able to build on that example, I hope. If you can't add the previous_business_date to your holiday table, then it gets slightly more complicated (because you have to skip back through consecutive holidays AND weekends AND any more consecutive holidays - ie in UK you'd have to skip back through Easter Monday, the Easter Weekend and Good Friday - last busines day is what we call Maundy Thursday.
    HTH
    Regards Nigel

  • Is it possible to modify the Calendar object to only show working days?

    Is there a way to configure the Calendar selection, duration calculations, and notification dates in the system to only include working days (i.e. holidays and weekends are not counted and not available for selection)? This is particlular for Purchasing and Sourcing Modules.
    Thank you.

    This can be changed through registry:
    https://msdn.microsoft.com/en-us/library/ff800821%28v=ws.10%29.aspx
    You can do the change through group policy preferences, or some other method you prefer (ConfigMgr compliance settings for example).

  • SAP HR : Wrong working days displayed in Z report

    Dear Friends ,
    I have made a z report for SAP- Hr to show working days of employee of a particular month
    when I am running report for all the employees then working days are wrongly displayed in alv
    report but when I am running the report for a particular employee then the working days are
    correct . I have done debugging also , every thing is fine in debugging , Now I am confused
    where is fault I have to run the report for all employee.
    Kindly suggest .
    Regards
    Rihan
    SAP-abaper

    hye ,
    here, some code for your reference ,
    LOOP AT it_empall WHERE pernr EQ stru-pernr.
          SELECT SINGLE SUM( abwtg ) FROM pa2001
                              INTO absdays
                              WHERE pernr = it_empall-pernr
                              AND   endda BETWEEN p_begda AND p_endda
                              AND   begda BETWEEN p_begda AND p_endda.
    "FOR RESIGN
            select single begda from Pa0000 into enddt where pernr eq it_empall-pernr
                                                       and massn eq 'H6'.
    "FOR HIRING
             select single begda from Pa0000 into begdt where pernr eq it_empall-pernr
                                                       and massn eq 'H1'.
         totdays = p_endda - p_begda.
          totdays = totdays + 1.
         if enddt GT p_begda and enddt LT p_endda.
                           X = ( p_endda - enddt ) + 1 .
                           workdays = totdays - x - absdays.
                           stru-kaltg = workdays.
         elseif begdt GT p_begda and begdt LT p_endda.
                          X = ( begdt - p_begda ) .
                          workdays = totdays - x - absdays.
                          stru-kaltg = workdays.
         else .
                          workdays = totdays - absdays.
                          stru-kaltg = workdays.
         endif.
      ENDLOOP.
    Note : here p_begda AND p_endda are month start and end date.
              and begdt and enddt  (  these are  employee joined and resigned date)
    Pls suggest .....

  • How to show no. of actual working days in Payslip in case of +ve time mgt

    Dear Experts,
    We have a requirement of showing no. of actual working days in payslip, which should be Calendar Days-(Paid+Unpaid absence). I created an w/t 1WRD for actual working days. Our paid absence w/t is 2006 and unpaid absence is 2005 copied from /845 and /846 respectively, both the absences are included in absence valuation table and working fine in that respect. But issue is i wrote a small PCR for calculating actual working days like below:
    ZWRD
         NUM=TKSOLL Set
         NUM-E 2005
         NUM-E 2006
        ADDWTE1WRD
    But still its fetching full working days i.e. calendar days 30 or 31 not deducting paid or unpaid absence for a month.
    Pls help, what else should i do.
    Regards
    Tan

    Sorry, i am unable to paste RT, but its exactly as below
    01, April, 2011
    1WRD Working days     30.00
    2006  Paid Absence       2.00                
    02, May, 2011
    1WRD Working days     31.00
    2005  Unpaid Absence   1.00                 
    regards
    Tan

  • Can PB native calendar objects show non-working days?

    Hello all
    I have a question about the native controls of PB, who functoin as date pickers.
    Is there a way to make them show holidays in different color?
    I am working on PB11.5 and PB12.5 - non-pfc
    Thank you
    Arcady

    Hi,
    Welcome to SDN...!!!
    Please find below a list of tables for factory calendar:
    TFACD     Factory calendar definition
    TFACS     Factory calendar (display)
    TFACT     Factory calendar texts
    TFAIN     Calendar: Intervals for company holidays, special shifts
    TFAIT     Calendar: Text for factory calendar intervals
    THOC     Public Holiday Calendar
    THOCD     Public holiday definitions
    THOL     Public Holidays
    THOLT     Public holiday text
    Check last two tables it will help you for non-working days.
    Regards,
    Alok Tiwari

  • Showing current date and the last 250 working days

    Hi,
    we need to report the current day and the last 250 working days. How can I implement this into the BEx by using a variable for the current day selection. How can the selection of the last 250 working days work?
    Thanx
    René

    Hi Rene,
    I think that you have to go for a customer exit variable with multiple selections. The exit will calculate all these work days and place them into output for restriction.
    Best regards,
    Eugene

  • Calendar Rules showing the same day holiday as well as working day

    Hi All,
    I am using OBPM 10.3.
    I have created a holiday rule say "holi_rule" and declared a user defined holiday. I have created a Calendar rule and set "holi_rule" as holiday rule in calendar rule.
    When I am trying the below code
    calendarRule = Fuego.Lib.CalendarRule.fetch(calendarName : "India_Calendar_Rule");
    workDate = calendarRule.isWorkDate(time : timeObj.time);
    logMessage( " Is working day : "+workDate);
    boolean isHoliday = calendarRule.isHoliday(time : timeObj.time);
    logMessage( " Is holiday day : "+isHoliday );
    timeObj.time is a input which I getting from the BPM presentation object."Both the log messages are displaying as true. I am not sure why both are displaying as true. Can any one help me to fetch the user defined holiday as holiday?
    Thanks in advance
    -Narasimha

    Hi,
    I hope the timeObj.time that you have defined/fetching from presentation is a holiday which you have defined in Holiday Rule.
    Accoring to the Holiday rule it is a holiday but according to the working day that you have defined in Calendar Rue is also a working day.
    So you should make use of thest two logic to find out an actual working day
    if(calendarRule.isWorkDate(time : timeObj.time) == false && calendarRule.isHoliday(time : timeObj.time) == true) {
    //Put your logic here
    Bibhu

  • Working days formula and Crystal 7 - is it possible?

    Post Author: Tim F
    CA Forum: Formula
    Hi folks,
    Really hope someone can help, I'm struggling with writing a report that needs to show the difference between two dates in working days. I've found the same formula posted here several times but cannot get it to return a logical value in my report. I'm wondering if that might be because I'm using an older version of Crystal? The formula in question is this one:
    //Main formulaWhileReadingRecords;Local DateVar Start := ({PPV_COMPLAINTSEH.DTRECD});   Local DateVar End := ({PPV_COMPLAINTSEH.ACTCMPLTD}); Local NumberVar Weeks; Local NumberVar Days; Local Numbervar Hol;DateVar Array Holidays;
    Weeks:= (Truncate (End - dayofWeek(End) + 1 - (Start - dayofWeek(Start) + 1)) /7 ) * 5;Days := DayOfWeek(End) - DayOfWeek(Start) + 1 + (if DayOfWeek(Start) = 1 then -1 else 0)  + (if DayOfWeek(End) = 7 then -1 else 0);  
    Local NumberVar i;For i := 1 to Count (Holidays)do (if DayOfWeek ( Holidays&#91;i&#93; ) in 2 to 6 and      Holidays&#91;i&#93; in start to end then Hol:=Hol+1 );
    Has anyone come across an alternative way of doing this, or have any ideas why this formula is not working in my report? Any advice would be much appreciated,
    Regards,
    Tim

    Post Author: Charliy
    CA Forum: Formula
    You set up a Running Total.  Drag the filed you want Summed, Select Sum as the operation if that is not the default.
    Just below that you weill see Radio Buttons that say For Every Record, On Change of Group, On Change of Field, Use a Formula, etc - click the one that says Use a Formula.  The Blue Bos to its right will turn Red, click on it, this is where you put your formula: NOT(DATEPART('w',{table.date}) IN &#91;6,7&#93;)
    Save that, then just decide if you want it reset on a Change of Group, or Never (Grand Total).  Give it a name and put it on your report.

  • Current Workday SAP EXIT variable not aligned with correct work days

    Hello,
    I am trying to use the Current Workday variable within a report so that the data will only be refreshed when the calendar day is Monday - Friday. Users look at this report every day, but when they get the report on Monday we would like for the date to be restricted to the previous Friday, and then switch back to Monday's date when they view the report on Tuesday. In order to do this we have placed the Current Workday variable from the Calendar Date characteristic with an offset of negative 1, but it is showing Sunday's date when they look at the report on Monday.
    My questions are:
    -Does this variable use the factory calendar that can define the work days?
    -If so, which Factory calendar does it use? I have gone to the Tcode SCAL but I can see there are many different factory calendars and I have no idea which calendar this variable pertains to. I have also transferred the global settings for the factory calendar from the source system, and I see no change within the variable.
    -How can I see the program name behind this SAP Exit variable? My thinking is that I could at least look at the code to see if perhaps I can find out the factory calendar ID the variable refers to from there.
    Any help on this would be greatly appreciated! Until this is fixed I have to manually adjust this report every Monday and Tuesday morning!! Not ideal.

    Hi Kelly,
    I am not sure whether this can be done by an SAP Exit variable.
    But you may try this using a Customer exit variable by using the Function module DATE_COMPUTE_DAY.
    The function module "DATE_COMPUTE_DAY" will return the day by 1 to 7 when you input date.
    Monday : System will return value = 1
    Tuesday : System will return value = 2
    Wednesday : System will return value = 3
    Thursday : System will return value = 4
    Friday : System will return value = 5
    Saturday : System will return value = 6
    Sunday : System will return value = 7
    So input sy-datum to this FM and find the number of day. If it is Monday, the number will be 1.
    If output is 1, then offset date by -3 to that of Friday, else offset by -1 to previous day.
    Hope this helps,
    Regards,
    Hari

  • Sales per Working Days

    I have a requirement to report the average sales per number of working days in the period. I have created a function module that can access the factory calendar and compute the number of working days in a given year/month and have populated a key figure on each record with the number of work days in the period the transaction took place in.
    When I display the number of working days by year/period in a report of course it adds up the days from each transaction and gives false numbers. This seems like it should be a no brainer, but I can't find an easy solution. Can anyone help me with displaying the correct number?
    Thanks in advance.

    Hi
    Try this logic:
    create an avarage Working Days KF1.
    its the working days / Rec Count.
    This KF if you group on CalYearMonth will show the sum
    of the numbers for that motnh.
    then if you want you can take KF1 and create another KF,
    lets say KF2 that is total Sales / KF1.
    I hope it helps.
    Reg's
    Edan

  • Supressing non work day messages for material requirments on Work orders

    Message CN687, pretaining to delivery date of materials takes into account the factory calender/nonwork days of the calender associated to the plant. This message pops up for every material line item on a work order, One could understand how involved it can be if ther are a number of materials on a work order, as you would have to enter passed each warning before continuing.
    Is there a way without preforming a mod that will allow us to supress this message on the work order side. Supply chain still wants to see it, however maintenance does not?

    Hi,
    As per my understanding your planned order is scheuling for 2 days.Check teh capacity view in the std plang book and check the date on which the capacity is being shown.IF the same is not showing on 15th then the problem is with scheduling not with capacity load.
    Also check the factory calendar assigned to resource master data.Check the date 15th on the bucket capacity on resource master SNP bucket capacity view.If the same is showing as working day then the master data needs to be changes.
    Hope this can help.
    regards,
    kaushik

  • Display data for last working day of month

    Hi
    I am trying to chart values for the last six years but only to plot the value for the last working day of the month, except for the current month where I am taking an average of the month so far. Everything I've tried has so far failed spectacularly. Has anyone resolved a similar problem?

    If I understand your dilemma correctly, you may want to create a cross-tab and then create the chart off of the cross-tab. Is the data in your tables that you want to chart on something like this:
             4/30   5/30   6/30   7/31   8/29       Sept.
    Row 1    20      30      10      25      20    (avg for month) 
    Row 2    5         10      8       15     15    (avg for month)
    etc.
    If so, 1) can you show an example of the data and 2) what kind of chart do you want to create?

  • Team Calendar non-working days

    Hi Gurus,
    Is there a way we can configure the team calendar to show non-working days for the employee (public holidays, days off in part-time/shift work-schedules) in green for example?
    I haven't seen any configuration options for this, but I would expect it to show them somehow!?  Will we need to do custom development for this?
    Many thanks,
    Russell.

    Hi Russell,
    You can check this<a href="http://help.sap.com/saphelp_erp2005vp/helpdata/en/2f/d7844205625551e10000000a1550b0/frameset.htm">SAP Help</a> for additional info on the Team Calendar iView..
    ~Suresh
    Russell,
    I didn't think the "10 points offer" was open to all.. ideally, it should be to Duxton only.. You could probably open a customer message in OSS & seek SAP's clarification on Team Calendar
    Message was edited by: Suresh Datti

  • Date calculations based on working days

    I need to add date calculations to a worksheet to show the time elapsed between two actions.
    Just a straightforward subtraction works fine, but what I really need to be able to do is calculate the number of working days between the two point (as something taking 5 days over Christmas with the 2 bank holidays is different equivalent to something taking 3 days in a normal week)
    At the moment I'm exporting the data into excel for analysis of this, but would really like to be able to do it in Disco so that the end users can go straight to the report using viewer, rather than having to do the conversion for them.
    Is this possible?
    Cheers

    Hi,
    Every thing is possible, the Q is how complicated is it....
    My suggestion is to create a table with all the dates of the non-working days for ex:
    create a table with all the MON-THURSDAYS, union to this table the holidays you know of such as christmas and so on.
    After getting this table you can create a function that returns the number of working days between 1 date to another by subtracting the days exists in this table.
    I started with that, you are more then welcome to get ahead with it and let us know what happened...
    create table holiday
    D_date date,
    d_day varchar2(20)
    create or replace procedure holiday_proc is
    d_date date;
    begin
    d_date := trunc(sysdate);
    while d_date<'01-jan-2010'
    loop
    if to_char(trunc(d_date),'Day') not in ('Saturday ','Sunday ') then
    INSERT INTO Holiday (d_date,d_day)
    (select trunc(d_date),to_char(trunc(d_date),'Day') from dual);
    end if;
    d_date := d_date+1;
    end loop;
    commit;
    end holiday_proc;

Maybe you are looking for

  • What All Do I Need If I Want To Upgrade My Macbook Hard Drive?

    hey guys. i've tried reading up a little but i was hoping someone (or a few people) could give me some straight up answers. if i want to upgrade my macbook hard drive what all do i need? just the hard drive? or are there other pieces? also.. whats a

  • Setting ACI using Macros

    Hi All, I want to restrict access for each domain to its users emails: A user belonging to a domain has to see the users of its own domain. Here is my ACI: (targetattr = "*") (target = "ldap:///($dn),dc=acme,dc=net")(version 3.0;acl "Domain Restricti

  • Field exit for prps-usr00

    Hi, I have to update the table field PRPS-USR00 from the pre-defined list of values (i.e from the ztable I have to take the value to upate the table field prps-usr00). I found the user-exit value also (CNEX0001). Please advice how to go ahead.

  • Wrong conversion of source system after transport

    Hello, We ve got a a transport problem in our 3-3 Landscape. Connections for extraction are only between same systems ( f.e. dev to dev) BI Dev         BI Test       BI Prod R3 Dev         R3 Test      R3 Prod The conversion of source systems is on t

  • Alert for Inbound message errors

    Hi We are updating the inventory using ProductActivityNotification inbound XML message from SAP PI. But when it fails due to some error(e.g Shipping party invalid) , we need to raise an alert or send mail, Could you please let us know how to configur