如何排除特定时间段内的特定日期范围?

How to do I exclude a specific date range within a specific period?

我正在使用 SQL Server 2012,我需要我的 T-SQL 查询来排除特定时间段内的特定时间范围。

我的过滤逻辑是这样的:

提取介于 2016-07-012017-03-25 之间以及介于 2017-07-012018-03-25 之间的所有数据,并排除上述过滤期间内的所有星期六和星期日日期以上。

我的T-SQL查询如下:

SELECT * from Table1
 WHERE [CreatedOn] between ...
 AND DATENAME(dw,[CreatedOn]) NOT IN ('Saturday', 'Sunday')

我卡在如何正确编写逻辑 Line 2

这对你有用

SELECT * from Table1
WHERE 
(
    [CreatedOn] BETWEEN '2016-07-01' AND '2017-03-25' OR
    [CreatedOn] BETWEEN '2017-07-01' AND '2018-03-25'
)
AND ((DATEPART(dw, [CreatedOn]) + @@DATEFIRST) % 7) NOT IN (0, 1)

知识

The master database’s syslanguages table has a DateFirst column that defines the first day of the week for a particular language. SQL Server with US English as default language, SQL Server sets DATEFIRST to 7 (Sunday) by default. We can reset any day as first day of the week using

SET DATEFIRST 5

这会将星期五设置为一周的第一天。

@@DATEFIRST returns SET DATEFIRST 会话的当前值。

SELECT @@DATEFIRST

Reference

合并 BETWEENANDOR

SELECT 
    * 
from 
    Table1
WHERE 
    (
        [CreatedOn] BETWEEN '2016-07-01' AND '2017-03-25' OR
        [CreatedOn] BETWEEN '2017-07-01' AND '2018-03-25'
    )
    AND DATENAME(dw,[CreatedOn]) NOT IN ('Saturday', 'Sunday')
    AND CreatedOn NOT BETWEEN '2017-01-01' AND '2017-01-02' 

试试这个:

SELECT * from Table1
WHERE 
([CreatedOn] BETWEEN '2016-07-01' AND '2017-03-25'
 OR
[CreatedOn] BETWEEN '2017-07-01' AND '2018-03-25') 
AND DATENAME(dw,[CreatedOn]) NOT IN ('Saturday', 'Sunday')