【问题描述】
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;
基本上是解决了上述的问题,如有更好的方案,欢迎留言。