我有一个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 Date BETWEEN to_date('2011/02/25','yyyy-mm-dd') 
               AND to_date ('2011/02/27','yyyy-mm-dd');

其他回答

由于没有指定时间段的datetime将具有date 00:00:00.000的值,如果您希望确保获得范围内的所有日期,则必须为结束日期提供时间,或者增加结束日期并使用<。

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'

OR

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date < '2011/02/28'

OR

select Date,TotalAllowance from Calculation where EmployeeId=1 
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'

不要使用下面的语句,因为如果它们的时间是00:00:00.000,它可能会返回一些从2011/02/28开始的记录。

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

试着把日期放在# #之间 例如:

#2013/4/4# and #2013/4/20#

这对我很管用。

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

两件事:

使用引号 确保包括最后一天(结束于24) 选择日期,总津贴 从计算 EmployeeId = 1 and "2011/02/25" <= Date and Date <= "2011/02/27"

如果Date为DateTime。

我倾向于以这种方式进行范围检查,因为它清楚地显示了下限和上限。请记住,日期格式在不同的文化中有很大的不同。所以你可能要确保它被解释为一个日期。使用DATE_FORMAT(日期,'Y/m/d')。

(提示:使用STR_TO_DATE和DATE_FORMAT来切换范例。)