T-SQL如何在DATETIME =周末和工作日之后选择记录

时间:2013-12-13 16:58:42

标签: tsql datetime sql-server-2008-r2

我有一个名为DATETIME的{​​{1}}列的表格。我只需要选择[Date]列=周日和周六,以及周一至周五上午12:00至上午8:00和下午5:00至凌晨12:00的记录。

这是我的代码:

[Date]

当我检查结果时,我发现它丢失了表格中的某些记录,这些记录在“下班后”中有[日期]。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

有时格式化代码可以帮助您更好地查看逻辑(和/或)分组。

WHERE 

(DATEPART(weekday, [Date]) IN (1, 7)) --<-- Put an extra closing paren here to isolate this side of the disjunctive (OR)

OR

(
   DATEPART(weekday, [Date]) IN (2, 3, 4, 5, 6)
   AND (
          (CAST([Date] AS TIME) BETWEEN '12:00am' AND '8:00am') --<--the first and last paren are not necessary, but help you to visually isolate this side of the disjunctive (OR)
          OR 
          (CAST([Date] AS TIME) BETWEEN '5:00pm' AND '12:00:00am') --<-- same here
       )
)

答案 1 :(得分:0)

我明白了。我把最后'12:00:00'改为'11:59:59'。谢谢你的时间。