我想选择日期
之间的值表1
Code Period Datefrom dateto Value
001 07/2011 01/07/2009 10/07/2009 100
211 07/2009 01/07/2009 05/07/2009 200
从上表我想检查datefrom和dateto之间的日期,如果日期在datefrom之间或等于date,则意味着它应该返回empcode的值
尝试查询
SELECT Value
FROM table1
Where Period = '07/2009'
and Code = '211'
and Cast('02/07/2009' as Datetime) between datefrom and dateto
预期产出:
code value
211 200
以上查询显示空值,应返回200。
我的查询有什么问题?
答案 0 :(得分:3)
默认情况下,Cast('02/07/2009' as Datetime)
为您带来2月7日
请改用
SELECT Code, Value
FROM table1
Where
Period = '07/2009'
and Code = '211'
and CONVERT(DATETIME, '02/07/2009', 103) between datefrom and dateto
<强> BUT 强>
如果它们属于varchar类型,您可能必须将datefrom
和dateto
列转换为。
答案 1 :(得分:0)
SELECT Code, Value
from table1
where Period = '07/2009'
and Code = '211'
and DateFrom <='02/07/2009'
and DateTo >= '02/07/2009'
答案 2 :(得分:-1)
您可以使用以下查询
SELECT code
, value
FROM table1
WHERE period = '07/2009'
AND code = '211'
AND convert(datetime,'02/07/2009',101)
between
convert(datetime,datefrom,101) and convert(datetime,dateto,101)