利用SQL语句如何获得两个日期之间相差的天数

我想用SQL语句得到两个日期(date1、date2)之间相差的天数,返回值为数值型,其中date1为数据库里输入数据时的时间,date2为当前系统时间

用sysdate假设结束日期字段是end_date

添加这个判断条件:

where to_char("end_date",'YYYY') = to_char(sysdate,'YYYY') 判断年相同

and to_char("end_date",'MM') = to_char(sysdate,'MM') 判断月相同

and to_char("end_date",'dd') - to_char(sysdate,'dd') = 15 判断日相同

或者:

where to_char("end_date",'YYYY-MM-DD') - to_char(sysdate,'YYYY-MM-DD')=15

扩展资料:

注意事项

DATEDIFF返回跨两个指定日期的日期和时间边界数。 

语法:DATEDIFF ( datepart , startdate , enddate ) 

参数:datepart

是规定了应在日期的哪一部分计算差额的参数。下表列出了 Microsoft® SQL Server™ 识别的日期部分和缩写。

startdate是返回datetime或smalldatetime值或日期格式字符串的表达式。 因为smalldatetime只精确到分钟,所以当用smalldatetime值时,秒和毫秒总是 0。

如果只指定年份的最后两位数字,则小于或等于"两位数年份截止期"配置选项的值的最后两位数字的数字所在世纪与截止年所在世纪相同。大于该选项的值的最后两位数字的数字所在世纪为截止年所在世纪的前一个世纪。例如,如果 two digit year cutoff 为 2049(默认),则 49 被解释为 2049,2050 被解释为 1950。为避免模糊,请使用四位数的年份。

有关时间值指定的更多信息,请参见时间格式。有关日期指定的更多信息,请参见 datetime 和 smalldatetime。 

enddate是计算的终止日期。enddate 是返回 datetime 或 smalldatetime 值或日期格式字符串的表达式。

返回类型:integer

注释:startdate 是从 enddate 减去。如果 startdate 比 enddate 晚,返回负值。当结果超出整数值范围,DATEDIFF 产生错误。对于毫秒,最大数是 24 天 20 小时 31 分钟零 23.647 秒。对于秒,最大数是 68 年。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2020-12-24
求两个日期(date1、date2)之间相差的天数用datediff函数,返回值为数值型,可以用cast函数或者convert函数

declare @a datetime
set @a ='2013-04-09'
select cast((datediff(day,@a,getdate()))as int)

结果为:7

你的需求sql语句为
select cast((datediff(day,date1,date2 ))as int)

或者可以这样select convert(int,date2)-cast(date1 as int)本回答被网友采纳
第2个回答  推荐于2017-10-03

可以用datediff函数。

创建表及插入数据:

create table test
(begindate datetime,
enddate datetime);

insert into test values ('2015-01-01','2015-07-13')

执行:

select datediff(day,begindate,enddate) from test;

结果:

第3个回答  2013-04-16
用sysdate 假设结束日期字段是 end_date
那么就添加这个判断条件
where to_char("end_date",'YYYY') = to_char(sysdate,'YYYY') 判断年相同
and to_char("end_date",'MM') = to_char(sysdate,'MM') 判断月相同
and to_char("end_date",'dd') - to_char(sysdate,'dd') = 15 判断日相同
当然 不知道这样是否可行
where to_char("end_date",'YYYY-MM-DD') - to_char(sysdate,'YYYY-MM-DD')=15
你都可以试一下 希望能够帮助你
第4个回答  2013-04-16
select Datediff(dd,'[输入的时间]',getdate()) <=====Datediff()函数去看看吧,能对数据库的时间操作的。dd表示的是日期。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网