从我的查询中排除周末

Exclude weekends from my query

我有一个查询工作正常。 该查询基本上检索从当前日期起 6-8 天前的数据。我想在测量数据的年龄时排除周末。

示例:如果一条记录是周五注册的,那么周一早上它会显示为 4 天,但实际上只有 2 天,因为周六和周日不应该计算在内。

我试过了,但似乎不起作用:

Select id, name, CreatedDate
from table
where 
CreatedDate <= DATEADD(day, -6, GETDATE()) AND CreatedDate >= DATEADD(day, -8, GETDATE()) -- here I get data between 6-8 days old
 AND ((DATEPART(dw, CreatedDate) + @@DATEFIRST) % 7) NOT IN (0, 1) -- Here im trying to exclude weekends

我做错了什么?

你可以试试:

     WHERE DATEPART(dw, date_created) NOT IN (1, 7);

试试这个:

Select id, name, CreatedDate
from table
where CreatedDate < GETDATE()-6 and CreatedDate > GETDATE()-8 and
((DATEPART(dw, CreatedDate) + @@DATEFIRST) % 7) NOT IN (0, 1)

您可以查看日历并尝试此查询

// Logic is very simple. 
// See calendar and try.
// If today is Monday, then Prev8workingdays will include 
// 8 working days + 2 weekends = 12 days. 
// Then result will be dateadd(day,-12, getdate()) = 12 days before today.
// Same logic for other days week
DECLARE @Prev8workingdays date = CASE
    WHEN datepart(dw, getdate()) IN (2,3,4) THEN dateadd(day,-12, getdate()) 
    WHEN datepart(dw, getdate()) IN (1) THEN dateadd(day,-11, getdate()) 
    ELSE dateadd(day,-10, getdate())
    END
DECLARE @Pre6WorkingDay date = CASE
        WHEN datepart(dw, getdate()) IN (2) THEN dateadd(day,-10, getdate()) 
        WHEN datepart(dw, getdate()) IN (1) THEN dateadd(day,-9, getdate()) 
        ELSE dateadd(day,-8, getdate())
    END

SELECT sd.* FROM
@SampleDate sd
WHERE sd.CreatedDate >= @Prev8workingdays AND sd.CreatedDate <= @Pre6WorkingDay

参考linkDATEADD