获取 SQL Server 中两个日期(星期五除外)之间的日期差异



我有以下两个日期:

startDate = '2017-04-04'  and  endDate = '2017-04-12'

我想找到这两个日期之间的总天数,不包括使用 SQL Server 'Fridays'

来自SQL服务器专家的任何帮助将不胜感激!!提前感谢!!

您可以使用DATENAME来检查'Friday'执行此操作,如下所示:

DECLARE @startDate DATETIME
DECLARE @endDate DATETIME
SET @startDate = '2017-04-04'
SET @endDate = '2017-04-12'
Declare @count int
set @count=0
    while @startDate < @endDate
    Begin
        IF DATENAME(dw, @startDate) <> 'Friday'
            SET @count = @count + 1
        SET @startDate = DateAdd(d, 1, @startDate)
    END
select @count

这将导致:

7

只需将以下子句添加到您的查询中

select count(*) from table
where startDate >= '2017-01-12' and endDate <= '2017-04-27' 
and datename(WEEKDAY,startdate))<>'Friday'

最新更新