Latest Number of Consecutive Days ("Current Streak")

Using SQL Server (On Azure)
I am trying to figure out how to get the latest number of consecutive days in an SQL query.
I have a habit tracking app in which I keep track of best streaks, originally I was storing this "Streak" value as it's own column in the Habit table and changing it directly. This of course led to incorrect syncing and accuracy issues. I realize
the best way to do it is to calculate from existing data.
I simplified the 2 tables as listed below:
Habit
id (the habit id)
Name (the name of the habit)
Target (the target number of entries required to be considered completed)
HabitEntry
id (the habit entry id)
HabitID (the corresponding habit id)
EntryDate (the date and time of the entry)
Looking to get a query that looks something like this:
SELECT habit.id, habit.Name, (*subquery*) as 'CurrentStreak' from habit join habitentry on habit.id = habitentry.habitid
And outputs something like this:
1, 'Exercise Daily', 7
If the habit's target is 2, there must be 2 entries within that date to be considered completed and to add to the streak.
Not sure if this complicates things, but days are measured from 3:00am to 3:00am, any help is greatly appreciated.

Figured I'd throw this in just for the fun of it. :)
IF OBJECT_ID('tempdb..#Habbit') IS NOT NULL DROP TABLE #Habbit
CREATE TABLE #Habbit (
ID INT PRIMARY KEY,
Name VARCHAR(255),
[Target] INT
INSERT #Habbit (ID,Name,Target) VALUES
(1,'Three Day Thing', 3),
(2,'Four Day Thing', 4),
(3,'Five Day Thing', 5)
--=============================================
IF OBJECT_ID('tempdb..#HabitEntry') IS NOT NULL DROP TABLE #HabitEntry
CREATE TABLE #HabitEntry (
UserID INT,
HabbitID INT,
EntryDate DATETIME
INSERT #HabitEntry (UserID,HabbitID,EntryDate) VALUES
(1, 1, '20150101 06:35:30'),
(1, 1, '20150102 08:35:30'),
(1, 1, '20150103 08:35:30'),
(1, 1, '20150110 09:35:30'),
(1, 1, '20150112 10:35:30'),
(1, 1, '20150115 22:35:30'),
(1, 1, '20150116 23:35:30'),
(1, 1, '20150117 00:35:30'),
(1, 1, '20150118 01:35:30'),
(1, 1, '20150122 04:35:30'),
(1, 1, '20150124 05:35:30'),
(1, 1, '20150126 15:35:30'),
(1, 1, '20150127 10:35:30'),
(2, 3, '20150101 06:35:30'),
(2, 3, '20150102 06:35:30'),
(2, 3, '20150103 02:35:30'),
(2, 3, '20150104 06:35:30'),
(2, 3, '20150105 06:35:30'),
(2, 3, '20150108 06:35:30'),
(2, 3, '20150110 06:35:30'),
(2, 3, '20150111 06:35:30'),
(2, 3, '20150112 06:35:30'),
(2, 3, '20150113 06:35:30'),
(2, 3, '20150114 06:35:30'),
(2, 3, '20150122 06:35:30'),
(2, 3, '20150123 06:35:30')
--=============================================
DECLARE @MinDate DATE, @RangeSize INT
SELECT @MinDate = DATEADD(dd, -1, MIN(he.EntryDate)) FROM #HabitEntry he
SELECT @RangeSize = DATEDIFF(dd, @MinDate, MAX(he.EntryDate) + 1) FROM #HabitEntry he
IF OBJECT_ID('tempdb..#CalRanges') IS NOT NULL DROP TABLE #CalRanges
SELECT TOP (@RangeSize)
DATEADD(dd, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), @MinDate) AS [Date],
DATEADD(hh, 3, DATEADD(dd, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), CAST(@MinDate AS DATETIME))) AS BegRange,
DATEADD(hh, 27, DATEADD(dd, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), CAST(@MinDate AS DATETIME))) AS EndRange
INTO #CalRanges
FROM sys.all_objects ao
--=============================================
;WITH cte AS (
SELECT
cr.Date,
he.UserID,
he.HabbitID,
he.EntryDate,
COALESCE(LAG(CASE WHEN he.EntryDate IS NOT NULL THEN cr.Date END, 1) OVER (PARTITION BY he.UserID, he.HabbitID ORDER BY cr.Date), '19000101') AS PrevDate
FROM
#CalRanges cr
JOIN #HabitEntry he
ON he.EntryDate BETWEEN cr.BegRange AND cr.EndRange
--AND he.UserID = 1
), cte2 AS (
SELECT
c.*,
CASE WHEN DATEDIFF(dd, c.PrevDate, c.Date) <> 1 THEN ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) END ConseqGroup
FROM cte c
WHERE c.Date <> c.PrevDate
), cte3 AS (
SELECT
c2.*,
CAST(SUBSTRING(MAX(CAST(c2.Date AS BINARY(4)) + CAST(c2.ConseqGroup AS BINARY(4))) OVER (PARTITION BY c2.UserID, c2.HabbitID ORDER BY c2.Date), 5, 4) AS INT) AS ConseqGroupFill
FROM cte2 c2
), cte4 AS (
SELECT
c3.UserID,
c3.HabbitID,
h.Name AS HabbitName,
MIN(c3.EntryDate) AS BegDate,
MAX(c3.EntryDate) AS EndDate,
COUNT(*) AS DaysInSeries
FROM
cte3 c3
JOIN #Habbit h
ON c3.HabbitID = h.ID
GROUP BY
c3.UserID,
c3.HabbitID,
c3.ConseqGroupFill,
h.Name
HAVING
COUNT(*) >= MAX(h.Target)
-- SELECT * FROM cte4
SELECT
c4.*
FROM (SELECT DISTINCT he.UserID, he.HabbitID FROM #HabitEntry he) AS a
CROSS APPLY (
SELECT TOP 1
FROM cte4 c4
WHERE a.UserID = c4.UserID
AND a.HabbitID = c4.HabbitID
ORDER BY c4.BegDate DESC
) c4
HTH,
Jason
Jason Long

Similar Messages

  • Latest Number of Consecutive Weeks

    I recently posted a similar question about getting the latest number of consecutive days.
    I thought with that information I'd be able to do the same for consecutive weeks, but I was wrong...
    I tried some queries using a calendar table, but no luck with getting the right results.
    Hate to ask again, but I've been stuck on it for the last 4 hours, can't seem to figure it out.
    I have a habit tracking app.
    I need the latest number of consecutive entries, by week.
    Here is some sample data:
    DECLARE @entries TABLE (ID INT IDENTITY, habitID INT, date DATETIME)
    INSERT INTO @entries (habitID, date) VALUES
    (1, '20150218'),(1, '20150225')
    DECLARE @habits TABLE (habitID INT, habitStartDate DATE, habitEndDate DATE)
    INSERT INTO @habits (habitID, habitStartDate, habitEndDate) VALUES
    (1, '2015-02-16',NULL)
    There is 1 habit, with 2 entries.
    The resulting query should return: 2
    This is because the last 2 weeks have had entries, and since this week is still current, we have until the end of the week to make an entry.
    But let's say this week goes by, and there have been no entries.
    Then next week, the result from the same query should return: -1

    Here's what I did:
    alter table calendar add HabitWeekStart DATETIME
    alter table calendar add HabitPrevWeekStart DATETIME
    alter table calendar add HabitWeekEnd DATETIME
    alter table calendar add HabitPrevWeekEnd DATETIME
    alter table calendar add HabitWeekEndTS DATETIME
    alter table calendar add HabitPrevWeekEndTS DATETIME
    update calendar
    SET
    HabitWeekStart = DATEADD(HOUR,27,WeekStart ),
    HabitPrevWeekStart = DATEADD(HOUR,27,PrevWeekStart),
    HabitWeekEnd = DATEADD(HOUR,27,WeekEnd ),
    HabitPrevWeekEnd = DATEADD(HOUR,27,PrevWeekEnd ),
    HabitWeekEndTS = DATEADD(HOUR,27,WeekEndTS ),
    HabitPrevWeekEndTS = DATEADD(HOUR,27,PrevWeekEndTS)
    DECLARE @entries TABLE (ID INT IDENTITY, habitID INT, date DATETIME)
    INSERT INTO @entries (habitID, date) VALUES
    (1, '20150218'),(1, '20150225'), (2, '20150218')
    DECLARE @habits TABLE (habitID INT, habitStartDate DATE, habitEndDate DATE, target INT)
    INSERT INTO @habits (habitID, habitStartDate, habitEndDate, target) VALUES
    (1, '2015-02-16',NULL,1 ),(2, '2015-02-16',NULL, 1)
    IF EXISTS (SELECT 'x' FROM tempdb.sys.tables WHERE name LIKE '#seq%') DROP TABLE #seq
    CREATE TABLE #seq (habitID INT, ID INT, today DATE, seq INT, target INT, hits INT, habitStartDate DATE, habitEndDate DATE)
    CREATE CLUSTERED INDEX IDXc_HabitID ON #seq (habitID)
    INSERT INTO #seq (habitID, ID, today, seq, target, hits, habitStartDate, habitEndDate)
    SELECT a.habitID, CASE WHEN COUNT(e.id) >= a.target THEN MAX(e.ID) ELSE NULL END AS ID, a.today, ROW_NUMBER() OVER (PARTITION BY a.habitID ORDER BY a.today) AS seq, a.target, COUNT(e.id) AS hits, habitStartDate, habitEndDate
    FROM (
    SELECT e.habitID, c.today, e.target, habitStartDate, habitEndDate
    FROM @habits e
    INNER JOIN calendar c
    ON c.today BETWEEN e.habitStartDate AND COALESCE(e.habitEndDate,CURRENT_TIMESTAMP)
    GROUP BY habitID, today, e.target, habitStartDate, habitEndDate
    ) a
    LEFT OUTER JOIN @entries e
    ON a.habitID = e.habitID
    AND DATEADD(SECOND,-10801,e.date) BETWEEN a.today AND DATEADD(SECOND,86459,a.today)
    GROUP BY a.habitID, a.today, a.target, habitStartDate, habitEndDate
    IF EXISTS (SELECT 'x' FROM tempdb.sys.tables WHERE name LIKE '#base%') DROP TABLE #base
    CREATE TABLE #base (habitID INT, habitStartDate DATE, habitEndDate DATE, habitWeekStart DATE, entries INT, seq INT)
    CREATE CLUSTERED INDEX IDXc_habitID ON #base (habitID)
    CREATE NONCLUSTERED INDEX IDX_habitID_Seq ON #base (habitID, seq) INCLUDE (habitStartDate, habitEndDate, habitWeekStart, entries)
    INSERT INTO #base (habitID, habitStartDate, habitEndDate, habitWeekStart, entries, seq)
    SELECT h.habitID, h.habitStartDate, h.habitEndDate, c.habitWeekStart, COUNT(e.ID) AS entries, ROW_NUMBER() OVER (PARTITION BY h.habitID ORDER BY c.habitWeekStart) AS seq
    FROM @habits h
    INNER JOIN calendar c
    ON c.today BETWEEN h.habitStartDate AND COALESCE(h.habitEndDate,CURRENT_TIMESTAMP)
    LEFT OUTER JOIN @entries e
    ON c.today = e.date
    AND h.habitID = e.habitID
    GROUP BY h.habitID, h.habitStartDate, h.habitEndDate, c.habitWeekStart
    ;WITH rCTE AS (
    SELECT habitID, habitStartDate, habitEndDate, seq, habitWeekStart, entries, CASE WHEN entries > 0 THEN 1 ELSE 0 END as streak
    FROM #base
    WHERE seq = 1
    UNION ALL
    SELECT r.habitID, r.habitStartDate, r.habitEndDate, b.seq, b.habitWeekStart, b.entries, CASE WHEN b.entries > 0 THEN r.streak+1
    WHEN b.entries = 0 AND r.entries = 0 THEN r.streak-1
    ELSE -1 END as streak
    FROM rCTE r
    INNER JOIN #base b
    ON r.habitID = b.habitID
    AND r.seq + 1 = b.seq
    ), rCTEw AS (
    SELECT id, habitID, today, seq, CAST(CASE WHEN id IS NULL THEN 0 ELSE 1 END AS INT) AS streak, hits, target, habitStartDate, habitEndDate
    FROM #seq
    WHERE seq = 1
    UNION ALL
    SELECT e.id, e.habitID, e.today, e.seq, CAST(CASE WHEN r.ID IS NOT NULL AND e.ID IS NOT NULL THEN r.streak+1
    WHEN e.ID IS NULL AND r.ID IS NULL THEN r.streak-1
    WHEN e.ID IS NOT NULL AND r.ID IS NULL THEN 1
    ELSE 0
    END AS INT) AS streak, e.hits, e.target, r.habitStartDate, r.habitEndDate
    FROM rCTEw r
    INNER JOIN #seq e
    ON r.habitID = e.habitID
    AND r.seq+1 = e.seq
    SELECT habitID, habitStartDate, habitEndDate, today, entries, streak, 'weekly' AS period
    FROM rCTE r
    INNER JOIN calendar c
    ON r.habitWeekStart = c.today
    AND c.weekEndTS > DATEADD(DAY,-7,CURRENT_TIMESTAMP)
    AND c.weekEndTS < CURRENT_TIMESTAMP
    UNION ALL
    SELECT habitID, habitStartDate, habitEndDate, today, hits, streak, 'daily'
    FROM rCTEw
    WHERE today = CAST(DATEADD(DAY,-1,'2015-03-02') AS DATE)
    ORDER BY period, habitID, today
    and here's the result:
    habitID habitStartDate habitEndDate today entries streak period
    1 2015-02-16 NULL 2015-03-01 00:00:00.000 0 -4 daily
    2 2015-02-16 NULL 2015-03-01 00:00:00.000 0 -11 daily
    1 2015-02-16 NULL 2015-02-23 00:00:00.000 1 2 weekly
    2 2015-02-16 NULL 2015-02-23 00:00:00.000 0 -1 weekly

  • How to get the last(latest or previous) working day

    hi,
    using sysdate we may be getting today's date and sysdate-1 will be fetching the yesterday's date. but if sysdate-1 turns to be sunday or a holiday then we need to get the previous date to that holiday date .THe list of holidays are in lt_list_holidays. The Holiday date shall be the holiday_date column. I need a query which displays the last (latest or previous) working day ..
    Please advice
    Edited by: vine on Jul 20, 2010 5:30 AM
    Edited by: vine on Jul 20, 2010 5:51 AM

    Hi,
    vine wrote:
    hi ,
    THe queery seems to be fine but in the middle if we have any holidays and the holidays are in lt_list_holidays table . the name of the holiday date is holiday_date in lt_list_holiday.Is the name of the holiday important? I'll assume not. I'll also assume you have a column d (a DATE) that is the date of the holiday.
    >
    Please adviceThat's quite a different problem from what you first posted.
    Instead of posting a question x, waiting for someone to answer it, and then saying that the problem is really y, don't you think it would be better to post question y in the first place?
    You can do something like this:
    WITH     prev_days     AS
         SELECT     TRUNC (SYSDATE) - LEVEL     AS a_date
         FROM     dual
         CONNECT BY     LEVEL <= 4     -- worst case (see below)
    SELECT     MAX (a_date)     AS previous_work_day
    FROM     prev_days
    WHERE     TO_CHAR (a_date, 'Dy', 'NLS_DATE_LANGUAGE=''ENGLISH''')
                   NOT IN ('Sat', 'Sun')
    AND     NOT EXISTS ( SELECT  1
                   FROM    lt_list_holiday
                   WHERE   d     = prev-days.a_date
    ;Where I work, holidays are never consecutive, in fact, they are always at least 7 days apart, so I can be sure that a period of 4 consectuive days will always contain at least one work day. (There may be two weekend days plus one holiday; that's the worst case.) If you can have two or more holidays in a row, or holidays spaced 3 days apart (so that one might fall on a Friday, and the other on Monday), then increase the "magic number" 4 in
         CONNECT BY     LEVEL <= 4     -- worst caseto something appropriate. If you put it too high (say 10), no serious harm is done.

  • How to find consecutive days?

    Hi I have a requirement, where I need to find all employees who have taken 5 consecutive days off in one week.
    I am trying to build a query in BI, which can identify these records, but of no avail. I am wondering if I can do this in visual Composer. My data output currently looks like this in a table.
    Employee number     calendar day    time-off hours
      100                           6/8/2009         8
      100                           6/9/2009         8
      100                           6/10/2009       8
      100                           6/11/2009       8
      100                           6/12/2009       8
      101                           6/1/2009         8
      101                           6/5/2009         8
      I like to loop through this table, somehow, and identify that employee 100, has 5 consecutive days off, but not 101.
      I like to filter those employees who do not have 5 consecutive days off, and just show those who have 5 days off, like employee number 100. My output should look like, this
    Employee number     calendar day    time-off hours
      100                           6/8/2009         8
      100                           6/9/2009         8
      100                           6/10/2009       8
      100                           6/11/2009       8
      100                           6/12/2009       8
    Any ideas will be greatly appreciated. I am trying out dynamic expression, but cannot find a way to access the first row of data, while processing the second row.

    Hi
    Why dont you try with time characteristics '0CALWEEK'. Add '0CALWEEK' to your infocube & map it with the date which you already have in the table. Now consider the your example for employee '100' -
    100 6/8/2009 8
    100 6/9/2009 8
    100 6/10/2009 8
    100 6/11/2009 8
    100 6/12/2009 8
    by adding Calweek you will get - 100   24.2009 (that is 24 th week)  40 hrs.
    Now in your query divide this 40 hrs (that is total working hours in week) with daily min working hrs. (In your case assume it 8 Hrs per day). So in query you will get number of working days in a week for each employee. From this you can easily find out how many leaves each employee has taken.
    I think this is what you are looking for.
    Regards
    Sandeep

  • 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

  • Number of working days in customer exit?

    Hi, this is actually an extension to the following thread.
    How to calculate number of working days
    I have very similar requirement. Determine the number of working days (excluding weekends and holidays) from 2 given dates. But the <b>difference here</b> is that, one of the date in the calculation is the<b> current date.</b>
    1: Creation Date - this is present as infoobject in the ODS.
    2: Current Date - this is 'today''s date.
    And, No. of Working days(Zworkdays)  = Current Date - Creation Date.
    So, as mentioned in the thread 305257 speaks about including the logic in the update rules, I can use system variable sy-datum to get the current date in update routine. But if the load is not scheduled for every day (say,once in 2 days), then when i report this infoobject Zworkdays on Day2, then it will hold Day1 calc rite?
    PLease correct me if I am wrong.
    Could you please help me with other approachs I can follow. One I can think is Customer Exit in Bex for the same.... but I am not sure how to do the same (i am new to Bex and Customer exit). Could any one of you please guide me how to achieve the same. I Have 0CalDate in the ODS also. 
    Any other ideas/inputs is greatly appreciated.
    Thanks in advance
    Ramya

    Hi,
    search for virtual key figures.
    Rgds.
    Juergen
    P.S. Thanks for assigning points
    Message was edited by:
            Jürgen Hemelt

  • Number of the day in the year

    Hi,
    I have a requirement to add the number of the day in the year to the message and concatenate with HHMM as shown below
    like this :1205001...12:HH,05:MM; 001(1st day of the year)
    ex2: 0204365...02:HH;04:MM;DDD:365(last day of the year)
    ex3: 0209236..02:HH;09:MM;DDD:236:(236th day of the year)...
    How can i achieve this? any standard functionality?
    please advise.
    Regads

    Hi ,
                 Is it the current system date you wanna concatenate?  Anyways this can be achieved by message mapping using standard functions
    input--------------------------------------------------------------------\
                                                                                concat()--------> target field
    currentdate()--->Transformdate(yyyy/MM/dd,hh:mm:DDD)----------------------/
    If its not system date then you can input any field like "2012/01/02"  or change the format of input date transformdate (the first field).
    Regards
    Anupam

  • 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

  • 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

  • Credit charges based on the number of credit days offered to the customer

    AOA,
    I have a scenario.
    We have credit charges based on the number of credit days offered to the customer. This scenario will be executed on credit sales only.
    Example of pricing, a product mobile is offered to customer A on 20 Days credit
    Mobile   $1000
    10 Days $1000
    20 Days $2500
    Total      $4500 (Invoice Amount)
    Any idea how can I acheive this in SAP.

    Customer A wants to buy product " Mobile "
    Scenario is of Credit sales. Pricing is as follows:
    Price                       $1000
    10 Days                  $1000
    Total After 10 days $2000
    20 Days                    $2500
    Total After 20 days $4500
    Gross Amount         $4500
    The amount of invoice will be $4500.
    If customer pays the amount with in 10 days, then customer only pays $1000.
    If customer pays the amount with in 20 days, then customer only pays $2000.
    If customer pays the amount after 20 days, then customer pays $4500.

  • To see the number of working days and leave of an employee for year

    HI SAP GURUS,
    I want to see the the number of working days and leave of all employees of the organisation for a year. Please tell me is there any report or any transaction code in sap to see the working days and leave for all employees.
    Thanks & Regards
    Surupa

    Hi,
    call transaction PT64.
    Best Regards
    Bernd

  • F110 DME payment file: add a number of lead days to posting and value date

    Hello,
    For an Italian company, the DME payment file (F110) needs to be checked and approved by an accountant after it is created. This takes 3 to 4 days after which the file is sent to the bank. The bank will reject the file if the value date  is three days late (date which the bank uses to process the file on). For fiscal reasons the accounting clerks need the have the same posting date as the value date
    I managed to set the value date in the DME files a couple of days later. The setting I used (FBZP -> bank determination -> value date) adds the number of lead days to the value date on the basis of the posting date as defined by the user in F110. For some reason I cannot set it to 0 days, it always adds up 1 day. Is that a normal effect or have I changed the settings in the wrong way?
    I found another setting in customising ("define value date rules") which seems to have the same functionality. In the help function it is said that the setting does not influence the payment program and that the program manages the value date. Is there another setting? Can this problem be solved without the help of a programmer?
    Thank you very much!
    René
    functional consultant
    Edited by: ConsultantSAINT-OBAIN on Apr 8, 2010 10:24 AM

    Here's a section of code that does exactly that:
    CALL FUNCTION 'DATE_CONVERT_TO_FACTORYDATE'
      EXPORTING
        CORRECT_OPTION                     = '+'
        DATE                               = G_WORKAREA3-CREATEDON
        FACTORY_CALENDAR_ID                = L_S_PLANT-FACTCAL_ID
      IMPORTING
    *   DATE                               =
       FACTORYDATE                        = L_FCDATE
      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.
      L_FCDATE = L_FCDATE + L_S_ZLEAD-/BIC/ZLEAD.
      CALL FUNCTION 'FACTORYDATE_CONVERT_TO_DATE'
        EXPORTING
          FACTORYDATE                  = L_FCDATE
          FACTORY_CALENDAR_ID          = L_S_PLANT-FACTCAL_ID
        IMPORTING
          DATE                         = L_DATE
        EXCEPTIONS
          CALENDAR_BUFFER_NOT_LOADABLE = 1
          FACTORYDATE_AFTER_RANGE      = 2
          FACTORYDATE_BEFORE_RANGE     = 3
          FACTORYDATE_INVALID          = 4
          FACTORY_CALENDAR_ID_MISSING  = 5
          FACTORY_CALENDAR_NOT_FOUND   = 6
          OTHERS                       = 7.
    * result value of the routine
      RESULT = L_DATE.

  • FM to calculate Number of working days adjusted for an employee -ABAP HR

    I have one requirement in which i have to Calculate "Number of working days adjusted" for an employee for a disability program.
    In this context i wanna know, if just get difference between two dates (i.e the duration for which employee was compensated ) based on Holiday calender...Will this give give me "Number of working days adjusted"  for an employee or i have to consider work schedule for an employee? If yes , Then please let me know sm FM to calculate number of working days between two dates speific to an employee.

    check
    HR_PERSONAL_WORK_SCHEDULE
    HR_GET_QUOTA_DATA

Maybe you are looking for