Get number of weekends between two dates in SQL

2019-02-25 16:24发布

问题:

I need to get the number of weekends between dates in sql as a function. I have tried but stuck up somewhere in the logic.

CREATE FUNCTION fnc_NumberOfWeekEnds(@dFrom DATETIME, @dTo   DATETIME)

RETURNS INT AS

BEGIN

   Declare @weekends int

   Set @weekends = 0

   While @dFrom <= @dTo Begin

      If ((datepart(dw, @dFrom) = 1))    

                  Set @weekends = @weekends + 1

                  Set @dFrom = DateAdd(d, 1, @dFrom)

   End

   Return (@weekends)

END

回答1:

Try replacing the if statement with this:

If ((datepart(dw, @dFrom) = 1) OR (datepart(dw, @dFrom) = 7))    

You should also check the end of the week to get the result.



回答2:

I tried out this logic with several edge cases and it seems to work.

SELECT DATEDIFF(d, @dFrom, @dTo)/7+1
    + CASE WHEN DATEPART(dw,@dFrom) IN (1,7) THEN -1 ELSE 0 END
    + CASE WHEN DATEPART(dw,@dTo) IN (1,7) THEN -1 ELSE 0 END

You can change the CASE statements depending on how you want to handle cases where the start or end date is in a weekend. In my case I'm not including the weekend if the start or end date is a Saturday or Sunday.



回答3:

Used below logic to calculate the no of Saturdays or Sundays between a start date and end date.

CREATE FUNCTION dbo.WEEKEND_COUNT
(
@Start_Date datetime,
@End_Date datetime
)
RETURNS int   
AS   
BEGIN
    Declare @count int = 0;
    while @Start_Date<=@End_Date
        Begin
        IF DatePart(WEEKDAY,@Start_Date) =  1 or DatePart(WEEKDAY,@Start_Date) =  7
        SET @count=@count+1
        SET @Start_Date=DateAdd(d,1,@Start_Date)
        END

return @count 
END

--Use below to get the count of Saturdays and Sundays

Select dbo.WEEKEND_COUNT('Your start date','your end date')


回答4:

This will give you the number of sunday between two dates

SELECT DateDiff(ww, @dFrom, @dTo) as NumOfSundays