需要帮助来创建一个SQL查询where子句

时间:2014-05-03 18:36:03

标签: sql sql-server filter where-clause select-query

我的桌子上有8列,其中2列是To& From这些数据类型为datetime。我想在这两个字段上执行带有一些过滤器的选择查询。

现在看下面的例子

Record X = From "5 May" to  "18 May" 

Filter 1: from "5 May" to "5 May" … x should show 

Filter 2: from "10 May" to "10 May" … x should show

Filter 3: from "1 May" to "1 May" … x should NOT show

Filter 4: from "19 May" to "19 May" … x should NOT show

Filter 5: from "18 May" to "18 May" … x should show 

Filter 6: From "4 May" to  "17 May" ….  X should show

Filter 7: From "4 May" to  "18 May" ….  X should show

Filter 8: From "4 May" to  "19 May" ….  X should show

Filter 9: From "5 May" to  "17 May" ….  X should show

Filter 10: From "5 May" to  "18 May" ….  X should show

Filter 11: From "5 May" to  "19 May" ….  X should show

Filter 12: From "2 May" to  "3 May" ….  X should NOT show

Filter 13: From "20 May" to  "25 May" ….  X should NOT show

所以基本上逻辑是 如果过滤日期范围和数据库日期范围之间有任何日期,则记录应显示在结果中。

你能帮帮我吗?看到所有这些配置后我感到很困惑。

3 个答案:

答案 0 :(得分:1)

SELECT *
FROM YourTable
WHERE from >= '5/5/2014'
  AND from < '5/6/2014'
  AND to >= '5/5/2014'
  AND to < '5/6/2014'

不会像过滤器1一样简单吗?或者您是否需要1个查询中的所有过滤器?

答案 1 :(得分:1)

您需要fromto列在过滤器定义的范围内,包括:

declare @filter_from datetime, @filter_to datetime

select *
from <table>
where col_from between @filter_from and @filter_to
  or col_to between @filter_from and @filter_to
  or @filter_from between col_from and col_to
  or @filter_to between vol_from and col_to

答案 2 :(得分:0)

试试这个

Select * from table_name where startDate between '4 May' and '18 May'
And endDate between '5 May' and '19 May'

谢谢。希望这有帮助

相关问题