根据日期参数从表中选择周末或工作日数据

时间:2013-08-17 14:52:24

标签: datetime sql-server-2012 case

如何根据工作日或周末从表格中选择数据,例如 如果日期是工作日,则只从表格中选择历史工作日数据。 如果日期是周末,则只选择历史周末数据。

我试图以这种方式做到这一点,但没有运气

DECLARE @MyDate DATE = '08/17/2013'

SELECT datename(dw,@MyDate)

SELECT * FROM MyTable
WHERE 
datename(dw,DateColumnInTable) IN ( 
CASE WHEN (datename(dw,@MyDate) IN ('Saturday','Sunday')) THEN '''Saturday'',''Sunday'''
ELSE  'Monday'',''Tuesday'',''Wednesday'',''Thursday'',''Friday'
END )

我可以在星期六和星期日看到我的表格中有很多数据,但这个查询给了我空白记录集。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

DECLARE @MyDate DATE = '08/17/2013'

IF (DATEPART(weekday, @MyDate) IN (1,7))
    SELECT * 
    FROM MyTable
    WHERE DATEPART(weekday, DateColumnInTable) IN (1,7)
ELSE
    SELECT * 
    FROM MyTable
    WHERE DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6

如果您想在一个条款中执行此操作,您可以执行以下操作,但可能会更糟糕:

SELECT *
FROM MyTable
WHERE (DATEPART(weekday, @MyDate) IN (1,7) AND DATEPART(weekday, DateColumnInTable) IN (1,7))
OR (DATEPART(weekday, @MyDate) BETWEEN 2 AND 6 AND DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6)