Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

sql server - Get number of weekends between two dates in SQL

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...