日期:2014-05-17  浏览次数:21139 次

关于month_between函数的用法,求解释!
各位:
  今天遇到个问题
  select months_between(lase_day(sysdate),to_Date('20120129','yyyymmdd')) from dual = 1
  select months_between(lase_day(sysdate),to_Date('20120130','yyyymmdd')) from dual = 0.989
 select months_between(lase_day(sysdate),to_Date('20120131','yyyymmdd')) from dual = 1

为什么中间那个值小于1 而最后一个值又等于1?

------解决方案--------------------
MONTHS_BETWEEN函数返回两个日期之间的月份数。如果两个日期月份内天数相同,或者都是某个月的最后一天,返回一个整数,否则,返回数值带小数,以每天1/31月来计算月中剩余天数。
------解决方案--------------------
假设d1和d2分别和months_between()函数的两个实参。
如果d1和d2是月份中相同的一天,或都是这个月的最后一天,则会返回整数。
否则会返回带小数的结果。
------解决方案--------------------
如果两个日期月份内天数相同(你第一条sql),
或者都是某个月的最后一天(你第三条sql),
返回一个整数,

否则(你第二条sql),
返回数值带小数,以每天1/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 calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.

权威的文档是这么说的;
Oracle calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
也就是 2月6日减去1月30日的天数除以31



PS:我做了下实验,由结果猜测,这个函数计算的精度远不只“天”高

SQL code
MONTHS_BETWEEN(LAST_DAY(SYSDATE),TO_DATE('20120130','YYYYMMDD'))
----------------------------
                                                      .990739247

SQL> /

MONTHS_BETWEEN(LAST_DAY(SYSDATE),TO_DATE('20120130','YYYYMMDD'))
----------------------------
                                                      .990742608

SQL> /

MONTHS_BETWEEN(LAST_DAY(SYSDATE),TO_DATE('20120130','YYYYMMDD'))
----------------------------
                                                      .990742981

SQL> /

MONTHS_BETWEEN(LAST_DAY(SYSDATE),TO_DATE('20120130','YYYYMMDD'))
----------------------------
                                                      .990743354

SQL>

------解决方案--------------------
OK,接我mm去了~~~~