Oracle的months_between(date1,date2)函式注意點

我叫阿狸貓發表於2014-01-07
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.


select 1/31 from dual;
      1/31
----------
0.03225806

這樣就能解釋了。


轉自 http://blog.sina.com.cn/s/blog_62e7fe6701014wtk.html

相關文章