2012-01-03 59 views
1

我想选择如何获得两个日期

表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 dateto装置,它应该返回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

什么错我的查询?

+1

是你的列datetime或VARCHAR?您可以尝试在where子句中使用'YYYYMMDD',以确保SQL Server不会混淆一个月和一天的情况。 – 2012-01-03 08:31:51

+0

你可以请张贴表的模式,以便我们知道数据类型?我认为代码和值是varchar权利? – 2012-01-03 08:33:39

回答

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 

你,可能要转换datefromdateto列太如果他们是VARCHAR类型的。

+0

我认为这是二月七日:-)你不需要转换那些列如果他们有日期时间值(而不是字符串) – 2012-01-03 08:37:43

+0

@HansKesting是的,错过了约会,但已经写了关于列8-) – 2012-01-03 08:39:24

0
SELECT Code, Value 
from table1 
where Period = '07/2009' 
and Code = '211' 
and DateFrom <='02/07/2009' 
and DateTo >= '02/07/2009' 
+0

错误!需要从英国格式转换字符串日期。查询是一样的,除了选择列表中的代码列 – 2012-01-03 08:32:59

-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) 
+0

错误!日期格式是英国/法国不是美国! – 2012-01-03 09:01:08