我有一个start_date和end_date。我想要得到这两个日期之间的日期列表。有人能帮我指出我的查询中的错误吗?

select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and Date between 2011/02/25 and 2011/02/27

这里Date是一个datetime变量。


当前回答

select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'

其他回答

我会选择

select Date,TotalAllowance from Calculation where EmployeeId=1
             and Date >= '2011/02/25' and Date < DATEADD(d, 1, '2011/02/27')

逻辑是>=包括整个开始日期,<不包括结束日期,因此我们在结束日期上添加一个单位。这可以适应几个月,例如:

select Date, ... from ...
             where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)

试试这个:

select Date,TotalAllowance from Calculation where EmployeeId=1
             and [Date] between '2011/02/25' and '2011/02/27'

日期值需要作为字符串输入。

为了确保您的SQL Server 2008及更高版本的查询能够适应未来,Date应该被转义,因为在以后的版本中它是一个保留字。

请记住,没有时间的日期将午夜作为默认值,因此这里可能没有正确的值。

select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

——如果数据类型不同

我们可以使用between来显示两个日期数据,但这将搜索整个数据并进行比较,因此对于巨大的数据,它会使我们的过程变慢,所以我建议每个人都使用datediff:

qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "

这里的日历是表,dt作为开始日期变量,dt2是结束日期变量。

SELECT CITY, COUNT(EID) OCCURENCES FROM EMP 
WHERE DOB BETWEEN '31-JAN-1900' AND '31-JAN-2900' 
GROUP BY CITY 
HAVING COUNT(EID) > 2;

该查询将查找DOB位于员工指定时间范围内的次数超过2次的城市。