解决oracle 的months_between的bug

【问题描述】

select months_between(to_date('2011-4-28','yyyy-MM-dd'),to_date('2011-2-28','yyyy-MM-dd'))
from dual;
MONTHS_BETWEEN(TO_DATE('2011-4
------------------------------
                             2
select months_between(to_date('2011-4-29','yyyy-MM-dd'),to_date('2011-2-28','yyyy-MM-dd'))
from dual;
MONTHS_BETWEEN(TO_DATE('2011-4
------------------------------
              2.03225806451613
select months_between(to_date('2011-4-30','yyyy-MM-dd'),to_date('2011-2-28','yyyy-MM-dd'))
from dual;
MONTHS_BETWEEN(TO_DATE('2011-4
------------------------------
                             2
2011-4-30日期大于2011-4-29,按理说第三个结果应该大于第二个结果,但是结果却是相反的。
后来查阅了oracle的官方文档,是这样解释的:(小数部分是按照一个月31天计算的)
MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
以上是我百度到的信息,链接接出处为:http://blog.sina.com.cn/s/blog_62e7fe6701014wtk.html

【解决策略】

SELECT countData-(last1-day1)/last1+(last2-day2)/last2 countData
FROM(SELECT 
( extract(year from date1)- extract(year from date2))*12+
( extract(month from date1)-extract(month from date2)) countData,
extract(day from date1) day1,extract(day from date2) day2,
SUBSTR(to_char(last_day(date1), 'yyyy-mm-dd'),9,2) last1,
SUBSTR(to_char(last_day(date2), 'yyyy-mm-dd'),9,2) last2
FROM (select date'2020-8-28' date1, date'2018-7-29' date2 from dual))
WHERE day1<=last1 AND day2<=last2;
基本上是解决了上述的问题,如有更好的方案,欢迎留言。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值