sql查询以获取日期之间的记录

时间:2014-12-16 10:21:57

标签: sql sql-server sql-server-2008

Id   | Status | Value  | CreatedDateTime
-----+--------+--------+------------------------
1    | Open   | Y      | 2014-12-10 14:03:10.100
2    | Open   | Y      | 2014-12-10 13:03:10.100
3    | Open   | N      | 2014-12-10 13:01:12.100
4    | Open   | Y      | 2014-12-10 05:02:11.100
5    | Open   | N      | 2014-12-09 15:03:10.100
6    | Open   | N      | 2014-12-08 14:03:10.100
7    | Open   | Y      | 2014-12-08 14:03:10.100

我想编写一个SQL查询来获取从2014-12-08 14:03:10.1002014-12-10 14:03:10.100的记录,Status也应该是Open Value = Y

我试过下面的sql查询 -

select * 
from mytable 
where CreatedDateTime between '2014-12-08 14:03:10.100' and '2014-12-10 14:03:10.100' 
  and Status in ('Open') and Value='Y'

3 个答案:

答案 0 :(得分:0)

这样的事情

SELECT Id,Status,Value,CreatedDateTime FROM <table>
WHERE CreatedDateTime BETWEEN '2014-12-08 14:03:10.100' AND '2014-12-10 14:03:10.100'
AND
Status = 'Open'
AND
Value = 'Y'

BETWEEN运算符是包含的,因此将包括上面的日期 - Link

编辑:删除了关于BETWEEN运算符如何工作的错误陈述

答案 1 :(得分:-1)

由于您的日期时间
试试这个:

 select * 
    from mytable 
    where convert(date,paid_on,103) between '2014-12-08' and '2014-12-10' 
      and Status in ('Open') and Value='Y'

答案 2 :(得分:-1)

试试这段代码

SELECT 
     Id
    ,Status
    ,Value
    ,CreatedDateTime 
FROM <table>
WHERE
    CreatedDateTime <= '2014-12-08 14:03:10.100'
    AND CreatedDateTime >= '2014-12-10 14:03:10.100'
    AND Status = 'Open'
    AND Value = 'Y'