select round(months_between(TRUNC(sysdate),to_date('2009-02','yyyy-mm'))),sysdate from dual;
具体使用
select to_date('20060302','yyyymmdd') date1,
to_date ('20060101','yyyymmdd')date2,
to_date('20060302','yyyymmdd')
-to_date('20060101','yyyymmdd') days,
(to_date('20060302','yyyymmdd')
-to_date('20060101','yyyymmdd'))/31
months_cal,
months_between(to_date('20060302','yyyymmdd'),
to_date('20060101','yyyymmdd')) months_tetween
from dual;
date1 date2 days months_cal months_tetween
2006-3-2 2006-1-1 60 1.93548387096774 2.03225806451613
解答下为什么是2.03225806451613
先计算年的差,然后月的差,日的差
通过3个结果,再计算。
oracle文档中是这样定义months-between的
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 calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
从20060101-20060301为整数月2(依照前面的文档说明)
剩下的20060301 - 20060302 为1天, 这一部分是小数部分, 1/31 = 0.03225806
加起来的结果是: 2+ 0.03225806 = 2.03225806