Number of a day occurence in a range of dates

Hi
I had a requirement of counting the number of times a particular day occurs between two dates.
For eg., Tuesday comes 9 times betweeen '01-mar-2008' and '15-apr-2008'
I have written the below function for it and it gives the desired output.
But am looking for a better logic, may be directly getting the count through a query instead of a function.
create or replace function day_occurance ( from_date date, to_date date) RETURN NUMBER is
   occ_day NUMBER := 3;
   from_weekday  NUMBER;
   ctr number := 0;
   temp_date date;
begin
   temp_date := from_date;
   while (temp_date <= to_date) loop
      from_weekday := to_char(temp_date, 'd');
      IF (from_weekday = occ_day) THEN
        ctr := ctr + 1;
      END IF;
      temp_date := temp_date + 1;     
   end loop;
   return ctr;
end;Thanks in advance.
Piks
null

like this ?
SQL> select count(*) from (
  2  select to_date('01-03-2008', 'DD-MM-YYYY') + rownum - 1 dt from dual
  3  connect by level <= to_date('15-04-2008', 'DD-MM-YYYY') - to_date('01-03-2008', 'DD-MM-YYYY') + 1)
  4  where trim(to_char(dt, 'DAY')) = 'TUESDAY' ;
  COUNT(*)
         7

Similar Messages

  • Selecting Missing Days from a given range of Date  from a table

    Dear Oracle Guru's
    Consider the following table
    txndetails
    Rundate date
    Txncnt Number
    userid varchar2(100)
    Data will be as follows
    Rundate txncnt userid
    17-Nov-2009 4 admin
    18-Nov-2009 7 admin
    21-Nov-2009 3 admin
    23-Nov-2009 4 admin
    We populate this table on the basis of txn generated. This is supposed to run daily based on the transactions. Certain days there wont be any transaction at all. hence there will be no entry on this table .
    At any given point of time , we would like to know the days on which there is no entries in this table
    In the above sample data, there is no entries on 19th, 20th and 22nd
    we have to list out those days
    I got confused while trying some methods
    Kindly guide me in this regard
    with warm regards
    Ssr

    Hi,
    As Centinul and Bhushan said, you need a list of all the possible dates; "CONNECT BY LEVEL <= x" is an efficient way to generate such a list in Oracle SQL.
    Once you have the list of all days, you can use MINUS, like Centinul or Bhushan did. You can also use an outer join, as shown below.
    WITH  extrema     AS
         SELECT     TRUNC (MIN (rundate))     AS start_date
         ,     TRUNC (MAX (rundate))     AS end_date
         FROM     txndetails
    all_days     AS
         SELECT     start_date + LEVEL - 1     AS a_date
         ,     start_date + LEVEL        AS next_date
         FROM     extrema
         CONNECT BY     LEVEL <= 1 + end_date - start_date
    SELECT     a.a_date
    FROM          all_days     a
    LEFT OUTER JOIN     txndetails     t     ON     t.rundate >= a.a_date
                                     AND     t.rundate <  a.next_date
    WHERE   t.rundate     IS NULL
    ;Remember that all DATEs include hours, minutes and seconds. In the list of all days that you generate, the hours, minutes and seconds will probably be 00:00:00; be careful if the hours, minutes and seconds in your actual DATEs are not always 00:00:00.
    The query above shows missing dates between the first date that is actually in the table and the last date in the table.
    In practice, most people are interested in a deffierent range, such as all dates between two given parameters, or all dates within the last year.
    If that's the case, you don't need the sub-query extrema; you can use the paremters (or compute the values) in all_days, based on dual.
    For example, to get the most recent 365 days:
    WITH     all_days     AS
         SELECT     TRUNC (SYSDATE) + LEVEL - 365     AS a_date
         ,     TRUNC (SYSDATE) + LEVEL - 364       AS next_date
         FROM     dual
         CONNECT BY     LEVEL <= 365
    SELECT     a.a_date
    ...          -- Same as beforeEdited by: Frank Kulash on Nov 23, 2009 10:54 AM

  • Help please! How would i know if a day is within a range of dates?

    Hi everyone!
    I'm new to java. I just want to ask for help about date manipulation.
    My situation is this:
    In a given company, they set their own first-day-of-the-week. And this first-day-of-the-week may change from time to time. Given a calendar, you will pick a date and automatically, the start and end date of that certain week should be displayed in the text field. But the start and the end week should conform to what they set as the first-day-of-the week.
    Example:
    first_day_of_the_week = tuesday
    picked_date = april 7, 2005 //which is a thursday
    the output should be:
    start_date = april 5, 2005 //a tuesday
    end_date = april 11, 2005 // a monday
    because april 7 is within the week april 5 to april 11, april 5 being the first day of that week.
    I would really appreaciate if someone could help me.
    Thank you in advance!

    >
    Example:
    first_day_of_the_week = tuesday
    picked_date = april 7, 2005 //which is a
    thursday
    the output should be:
    start_date = april 5, 2005 //a tuesday
    end_date = april 11, 2005 // a monday
    because april 7 is within the week april 5 to april
    11, april 5 being the first day of that week.
    I would really appreaciate if someone could help me.
    Thank you in advance!Algorithm...
    - Set 'start' = to picked_date
    - Use Calendar and 'picked_date' to decrement by one day until day of week is tuesday.
    - Set 'start' to date in Calendar.
    - Use Calendar and ''picked_date'' to increment by one day until day of week is tuesday.
    - Decrement by one.
    - Set 'end' to date in Calendar.

  • Number of business days (excluding holidays) ?

    Hi All,
    What is the SQL query to find number of business days (excluding holidays) between 2 given dates ?
    List of Holidays will be maintained as a separate table.
    I need a SQL query rather than a stored procedure or function.
    I am using oracle 9i.
    Thanks in advance.

    Does this thread help?
    Need to find number of business days - query pls

  • Count the number of days in the selected range using Customer exit

    Hi Experts,
    we have requirment where user is asking to add a column to report, which will have 'count of days for which key figure is having values' for each of the months and the Header would be 'Day Count'
    Please let me know if its possible using Customer exit?

    Hi,
    In our report we have two characteristics site no. and product and we have 6 key figures of type quantity and Input for the report is Fiscal year/period
    So in the report Key figures are populated with values for respective site no. and product combination
    Now the user wants new column in report which will have header u2018Day countu2019 and it should Simply count the number of days in the selected range that have a volume different than 0 for key figure
    Please let me know if more details are required

  • Get the number of working days based on factory calendr for a range of mont

    Dear all,
    We are using BI7.00 . In one of our reports we have the following requirement.
    The range of months will be given in the selection screen for example 01.2008 to 11.2008, when the query is executed, i want system to calculate the number of working days for each month of the year (for what values provided in the selection field ) and display the same. i.e., as mentioned below.
    Month                         days.
    01.2008                        22
    02.2008                        18
    03.2008                        25  etc., Kinldy provide steps for adopting the same. If it can be adopted only through customer exit also provide the code and parameters that has to be used.
    Regards,
    M.M

    hi,
    Try the following logic to find out the no.of working days in a month based on your calendar.
    parameters : mny(6).    " input format should be  yyyymm
    data : d1 like sy-datum,
           d2 like sy-datum,
           d3 like sy-datum,
           v_nds type i.
    concatenate  mny '01' into d1.
    CALL FUNCTION 'SLS_MISC_GET_LAST_DAY_OF_MONTH'
      EXPORTING
        DAY_IN            = d1
      IMPORTING
        LAST_DAY_OF_MONTH = d2
      EXCEPTIONS
        DAY_IN_NOT_VALID  = 1
        OTHERS            = 2.
    IF SY-SUBRC <> 0.
      MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    do 30 times.
      CALL FUNCTION 'DATE_CONVERT_TO_FACTORYDATE'
        EXPORTING
          CORRECT_OPTION      = '+'
          DATE                = d1
          FACTORY_CALENDAR_ID = ' A'    " your factory calendar ID
        IMPORTING
          DATE                = d3.
      if d1 = d3.
        d1 = d1 + 1.
        v_nds = v_nds + 1.
      else.
        d1 = d3.
      endif.
      if d3 ge d2.
        exit.
      endif.
    enddo.
    write : 'No of working days ', v_nds.
    hope it helps...
    regards,
    raju

  • FM to get number of working days in a date range for a calender

    Hi all,
           Can you tell me the Function Module which takes start date ,, end date and factory calender as input and gives back working days or number of working days as return.
    Win full points for the resolution...
    Thanks in Advance...
    Chandan Dubey

    Hi chandan,
    1. DATE_CHECK_WORKINGDAY
    This is one useful FM
    2. Try this code (just copy paste)
    IT DOES EXACTLY WHAT U REQUIRE.
    REPORT abc.
    data : num type i.
    parameters : frdate type sy-datum default '20051216'.
    parameters : todate type sy-datum default '20051221'.
    perform getinfo using frdate todate changing num.
    break-point.
    *& Form getinfo
    text
    FORM getinfo USING fromdate todate CHANGING numofdays type i.
    DATA : d TYPE sy-datum.
    d = fromdate - 1.
    DO.
    d = d + 1.
    IF d > todate.
    EXIT.
    endif.
    CALL FUNCTION 'DATE_CHECK_WORKINGDAY'
    EXPORTING
    date = d
    factory_calendar_id = '01'
    message_type = 'I'
    EXCEPTIONS
    date_after_range = 1
    date_before_range = 2
    date_invalid = 3
    date_no_workingday = 4
    factory_calendar_not_found = 5
    message_type_invalid = 6
    OTHERS = 7.
    IF sy-subrc = 0.
    numofdays = numofdays + 1.
    write :/ d.
    ENDIF.
    ENDDO.
    ENDFORM. "getinfo
    I hope it helps.
    Regards,
    Amit M.

  • How to calculate number of working days

    Hi experts,
    I need to determine the number of working days from two given dates. Below is my example.
    1. Posting Date
    2. Clearing Date
    3. Processing Time in Days
    The formula is:
    Processing Time in Days = Posting Date - Clearing Date
    However, the above result should exclude non-working days such as Public Holidays, Saturdays and Sundays.
    This is to be done in my Transfer Rule.
    Can someone help me with this.
    Points will be assigned as usual.
    Thanks!

    Hi,
    With referece to  Florin Wach Reply in the following link:
    Re: FM to get number of working days in a date range for a calender
    Use the update rule(routine) for <i>Processing Time in Days</i> as below:
      DATA: date_begin         TYPE sy-datum,
             date_end           TYPE sy-datum,
             current_date       TYPE sy-datum,
             working_indicator  TYPE SCAL-INDICATOR,
             workdays           TYPE I,
             factory_calendar   TYPE SCAL-FCALID.
       date_begin       = DATA_PACKAGE-PSTNG_DATE.
       date_end         = DATA_PACKAGE-CLEAR_DATE.
       factory_calendar = '01'.
       current_date = date_begin.
       DO.
          IF current_date > date_end.
             EXIT.
          ENDIF.
         CALL FUNCTION 'DATE_CONVERT_TO_FACTORYDATE'
              EXPORTING  DATE                 = current_date
                         FACTORY_CALENDAR_ID  = factory_calendar
              IMPORTING
                         WORKINGDAY_INDICATOR = working_indicator
              EXCEPTIONS
                   CALENDAR_BUFFER_NOT_LOADABLE = 1
                   CORRECT_OPTION_INVALID       = 2
                   DATE_AFTER_RANGE             = 3
                   DATE_BEFORE_RANGE            = 4
                   DATE_INVALID                 = 5
                   FACTORY_CALENDAR_NOT_FOUND   = 6
                   OTHERS                       = 7.
         IF SY-SUBRC <> 0.
            workdays = 0.
            MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
            EXIT.
         ENDIF.
         IF working_indicator IS INITIAL.
            ADD 1 TO workdays.
         ENDIF.
         ADD 1 TO current_date.
      ENDDO.   
    Result  = workdays.
    With rgds,
    Anil Kumar Sharma .P

  • Calculate number of working days in a month

    Hi All,
    I am trying to build a report to calculate the performance of a sales rep for the current month. This report has to exclude the holidays (saturday, sunday and one extra day in each month) in order get the exact performance. Could anyone suggest me on how to go about writing a Case statement which would get me the number of working days in a month excluding holidays.
    Thanks

    Hi,
    There are no direct oracle function that could be used to get the desired results.
    However you could try using something like
    SELECT COUNT( *)
    FROM
    (SELECT ROWNUM RNUM
    FROM ALL_OBJECTS
    WHERE ROWNUM <= TO_DATE('&1') - TO_DATE('&2') + 1
    WHERE TO_CHAR(TO_DATE('&2') + RNUM - 1, 'DY') NOT IN('SAT', 'SUN');
    Give the two date ranges that you want to look for with the highiest one first. i.e say for example - 01-FEB-2011 to 31-DEC-2010 would give the working days in JAN. However note that you might have to check for holidays related to that country/region (which could be added as a seperate table).
    If you need to get an extra day in addition to the weekends, please give the dates accordingly
    SQL> SELECT COUNT( *)
    2 FROM
    3 (SELECT ROWNUM RNUM
    4 FROM ALL_OBJECTS
    5 WHERE ROWNUM <= TO_DATE('01-FEB-2011') - TO_DATE('01-JAN-2011') + 1
    6 )
    7 WHERE TO_CHAR(TO_DATE('01-JAN-2011') + RNUM - 1, 'DY') NOT IN('SAT', 'SUN');
    COUNT(*)
    22

  • Calculating Number of Working Days

    Hi All,
    I'm creating a crystal report where I have to calculate the Number of Working Days between a date range, this should exclude the Weekends(done) but also exclude the public holidays which have defined in Holidays Calender.
    I'm not using procedure , Operating directly with tables.
    Any help would be appreciated.
    Regards

    Hello Pari,
    Check Exclude Holidays and weekends from Last7Day function link for function to exclude weekends.
    and How to query the number of working days between two dates to get holidays defined in holiday calander.
    Thanks,
    Neetu

  • Add number of working days

    I have to subtract a number of 'working days' of a date field in my message mapping.
    I wrote a user defined function. I used cal.add(Calendar.DATE, -3); on the instance cal of the class Calendar. It subtracts 3 days, but I have to subtract 3 'working days'.
    Has anyone a suggestion how to achieve this?
    Kind regards
    Frank

    Frank,
        Since you said that there is FM available in R/3 DATE_CHECK_WORKINGDAY. I would suggest you to do RFC Lookup and get the response if it not working day, then subtract 1 from the current day, and again do lookup to check whether its working day or not. Finally if you get the response as Working day, then subtract 3 from the day(not from the current date, instead the subtracted date , in my previous step).
    But  it will not solve your issue. The above I said is an approach. Because, consider the below example.
    Current day is Saturday, you r doing RFC lookup and getting response as not-working day. Hence on subtracting 1 you will get Friday, now again you are doing RFC look up , this time you will get response as working day , immediately you will subtract 3 from friday, Finally you will get the result as tuesday!!!!
    Do you think its correct? Yah sometimes, because while subtracting 3 from friday we have to make sure that thursday & wednesday must not be holiday. I think you got my example, If I'm wrong , please reply me back.
    Hope it clears.
    The above is an approach, its not the solution. If you look its good we have to apply logic to ahieve the result.
    Best Regards,
    raj.

  • Add number of business days to date field

    Hello, I noticed that there is not much discussion in the forum surrounding u201Cbusiness daysu201D so I hope this post/discussion/solution contributes to the content of this forum.
    I am using the following 3 formulas to try to Add number of business days (based upon a table field) to a specified date:
    1. Variable name = SetVar
    //Set Variable for Add Business Days:
    DateVar Array Holidays;
    DateVar Target:= CDate({TMS_MOVEMENT_EVT.EVT_DATE}); // Put your field name in here
    NumberVar Add:=  {DTCI_DOD_TRANS.TRANS}; // put the number of days here to add (a positive number)
    NumberVar Added := (0);
    2. Variable name = AddBizDays
    //Adding Business Days:
    EvaluateAfter({@SetVar});
    WHILE Added < Add
    Do (target := target +1;
        if dayofweek (target) in 2 to 6 and not (target in holidays)
            then Added:=Added+1
            else Added:=Added);
    Target
    3. Variable name = HOLIDAYS
    //Holiday Array Formula for the report Header:
    BeforeReadingRecords;
    DateVar Array Holidays := [
    Date (2003,12,25),   // you can put in as many lines for holidays as you want. 
    Date (2003,12,31)
    0
    I am successfully getting my data needed to make the necessary calculations and variable assignmentsu2026 I believe that my ISSUE is that I am not sure where to place these formulas into my report so they assign the variables and execute properly when previewing my report. I am curious if that is my issue, and if so, can someone provide me direction on where to put each of these formulas in my report.
    Currently, when I try to preview the report, I get the following Crystal Reports Error:  -u201CA number, currency amount, Boolean, date, time, date-time, or string is expected here.u201D
    Then Crystal automatically opens the AddBizDays formula and highlights the word added, see below RE: u201CWHILE Addedu201D
    For reference, my report has 3 groups, and I am displaying all of my output information (and locating my formulas) in the group footer #3 report section. I have moved them around to other report sections/groups/placements, but to no success.
    Thanks so much.
    Best, Matt

    I worked this out... FYI - for the benefit of all forum users:
    ADDING BUSINESS DAYS TO A CERTAIN DATE (excluding weekends and holidays)
    1. Variable name = AddBizDays
    //Adding Business Days:
    WhileReadingRecords;
    DateVar Array Holidays;
    DateVar Target:= CDate(); // Put your field name in here
    NumberVar Add:=  ; // put the number of days here to add (a positive number)
    NumberVar Added := (0);
    WHILE Added < Add
    Do (target := target +1;
        if dayofweek (target) in 2 to 6 and not (target in holidays)
            then Added:=Added+1
            else Added:=Added);
    Target
    2. Variable name = HOLIDAYS
    //Holiday Array Formula for the report Header:
    BeforeReadingRecords;
    DateVar Array Holidays := [
    Date (2003,12,25), // you can put in as many lines for holidays as you want.
    Date (2003,12,31)
    0
    ...too bad i don't get forum points for sharing this solution.
    Special thanks to KenHamady.com -- for sharing this solution.
    Sincerely,
    Matt

  • How to calculate a number of calendar days from a start date (e.g. 60 days from 3/10/2012)

    How to calculate a number of calendar days from a start date (e.g. 60 days from 3/10/2012)

    DT,
    If the starting date is in Column A, and you want to calculate what the date would be 60 days later, in Column B, write in Column B:
    =A+60
    Couldn't be much easier.
    Jerry

  • ABAP - Function module to get the number of working days between 2 days

    Hi gentlemen,
    I have been asked to produce a report that gives the number of working days between 2 days, based on a calendar.
    I didn't find anything...
    Has any of you already written a function module to get this ?
    A great thanks in advance.
    Jacques Lagrif

    Hi ,
    you can try this ,
    when you require the number of working days between D1 and D2
    Total No of Days will be
    D2 - D1
    No of holidays between D1 and D2 , use the FM HOLIDAY_GET
    Pass the From date , to date , and the factory calendar to get the of Holidays
    Total no of days - Number of Holidays will your Working days
    Regards,
    Sathya

  • Find row number of first cell in a relative range that is less than $B$3

    Thanks for any help. I've spent hours searching, trying, and reading iWork Help
    Example:   $B$3 = 3
    Column C
    1:  9
    2:  2
    3:  9
    4:  2
    5:  3
    6:  9
    7:  9
    Find the first occurrence that is less than $B$3 (=3) in the range C3:C6. Return the row # (relative to the range, or actual row number, I don't care)
    Fill Down the formula, so the next cell looks at the range C4:C7
    In this case, I want it to return Row 4 (not 5 or 2)
    Tried this with MATCH (last argument -1 or 1) which almost works, but if it finds an exact match, it returns that row (5) instead of the first one (4)

    The single formula in D2, filled down that column, returns the row number of every row where the value in column C is less than or equal to the value in $B$3.
    The second formula, which I placed in B4, but which can go wherever it's needed, searches a limited range of column D for the minimum value in that range.
    In the example, based on your initial question, the range is three cells.  In B4, it's D2:D4; in B5 it's D3:D5, etc., with Numbers automatically adjusting the cell references as the formula is filled down the column. In each case, the formula returns the minimum value it finds in the three cell range, which is the row number on which the value in column C first meets the condition (less than or equal to $B$3) within that three cell range.
    In the second example, the formula retrieves the same value (the row number) as above, but instead of displaying it, uses it as the row-offset value in an OFFSET statement to return the Date from the row where the row number was collected.
    NOTE: Looking back at it, I see that in my rush to other duties I made an error in this formula, setting the row offset too high. Revise the formula as shown below to get the date from the correct row:
    Existing: =IF(MAX(D2:D4)=0,"",OFFSET($A$1,MIN(D2:D4),0))
    Revised: =IF(MAX(D2:D4)=0,"",OFFSET($A$1,MIN(D2:D4)-1,0))
    You wrote:
    If I'm following the logic, it would require one column (like D in this example) for every set of rows searched (in my example, B5:B15  filled down, so the next search is B6:B16 and so on).
    No. Provided the values of X and Y are constant for each set of searches, you'll need an auxiliary column for each column of values to be searched. One auxiliary column is used to mark the rows in which the value in B meets the condition ">x", the second to mark the rows where the value in C meets the condition "<y".
    The search formula (above) searches a subset of its column and returns the lowest row number where the condition for that column is met,and either displays that number or uses it to return and display a date.
    Regards,
    Barry

Maybe you are looking for

  • Print Layout Designer for UDO

    Hi, Can we design report with print layout designer for UDO forms? If yes, how do we accomplish this? If not, is there any other alternative? I am using 2004B. Thanks.

  • In case of ERS, please enter tax code

    Hi Gurus, Is this the default setting of the system or a customized setting? If our supplier is subject to ERS, we need to enter tax code during PO creation via ME21N? Thanks in advance.

  • Folder action to change the label of the folder

    Hi all I would like to use Automator/Folder Actions to set the Label of the folder to show that it contains a file that was created or modified as follows: Red if in the last three days, Orange if over three days but less than seven; and Yellow if ov

  • Sound in an application

    I have downloaded spell-a-word to my iPad 2 but no matter what I do I cannot get the sound to work.  It appears to be at the highest level when I push the button at the top of the ipad.  On screen it says the volume is at 5 or 6. I have restarted the

  • 398: Flash.exe Application Error

    On Windows XP Pro. HP 8000 workstation. I see the following error when Flash Professional 8 tries to launch: 398: Flash.exe Application Error This happened suddenly, and nothing has been added to the workstation. The Flash encoder also presents a fat