SQL查询:选择损坏的日期范围

时间:2014-11-17 04:57:19

标签: sql sql-server

选择此日期的示例范围为 ONE QUERY February 1 2013 - February 28, 2013 AND February 1, 2014 - February 28, 2014

示例代码

select 
    tenantcode, 
    date 
from DAILY 
where 
    tenantcode = 'CMBINA15' 
    AND date between '02/01/2013' and '02/28/2013' 
    and '02/01/2014' and '02/28/2014'

当然,代码不会返回任何值。

3 个答案:

答案 0 :(得分:2)

试试这个。

SELECT tenantcode,
       date
FROM   DAILY
WHERE  tenantcode = 'CMBINA15'
       AND ( date BETWEEN '02/01/2013' AND '02/28/2013'
              OR date BETWEEN '02/01/2014' AND '02/28/2014' ) 

答案 1 :(得分:1)

'yyyy-MM-dd'格式设为CAST([Mydate] as Date)

select tenantcode, date from DAILY where tenantcode = 'CMBINA15' 
AND CAST([date] as Date) between 
(
CAST('2013-02-01' as DATE) and CAST('2013-28-02'  as DATE) )
OR CAST([date] as Date) between
CAST('2014-02-01' as DATE) and CAST('2014-28-02'  as DATE) )

答案 2 :(得分:0)

您必须使用强制转换或转换函数来获取双方的正确日期格式。所以它会匹配并给出结果。

或者您可以使用在传递非日期值时使用的ISDATE函数。

select ISDATE('02/01/2013'), CONVERT( varchar(10), @frdate1 , 101)

select tenantcode, date from DAILY where tenantcode = 'CMBINA15' 
AND 
( 
    CONVERT( varchar(10),[date] ,101) between 
        CONVERT( varchar(10), '2013-02-01'  ,101) and CONVERT( varchar(10), '2013-28-02'  ,101) 
    OR 
    CONVERT( varchar(10),[date]  ,101) between
        CONVERT( varchar(10), '2014-02-01' ,101) and CONVERT( varchar(10), '2014-28-02'   ,101) 
)