从我的查询中排除周末

时间:2017-04-10 13:27:27

标签: sql sql-server select getdate datepart

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

示例:如果记录是在星期五登记的,那么星期一早上会显示它已经过了4天,但它实际上只有2天,因为Satuday和星期日不应该计算。

我试过了,这似乎没有用:

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

我做错了什么?

3 个答案:

答案 0 :(得分:2)

你可以尝试:

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

答案 1 :(得分:2)

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

// 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

参考链接DATEADD

答案 2 :(得分:1)

试试这个:

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