Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Number of Months in Date Range (Not Between)

Status
Not open for further replies.

jasonhuibers

Programmer
Sep 12, 2005
290
0
0
CA
This returns the count of 3 months (which is correct):
SELECT round(MONTHS_BETWEEN (DATE '2012-12-07', DATE '2012-10-12') + 1) FROM dual;
Dec
Nov
Oct

However I am trying to return the count of 2 for the following:
SELECT round(MONTHS_BETWEEN (DATE '2013-01-07', DATE '2012-12-31') + 1) FROM dual;

This returns 1 which is incorrect - should return 2 as there is Jan and Dec...

 
Something like "Select count (distinct (reformat datefield as yyyy+mm)) from data source.

====================================
Sometimes the grass is greener on the other side because there is more manure there - original.

 
Added TRUNC and seems to do the trick...

SELECT MONTHS_BETWEEN (TRUNC(DATE '2012-12-07','MONTH'), TRUNC(DATE '2012-10-12','MONTH')) + 1 FROM DUAL;
SELECT MONTHS_BETWEEN (TRUNC(DATE '2013-01-07','MONTH'), TRUNC(DATE '2012-12-31','MONTH')) + 1 FROM DUAL;
 
Jason,

(See my post in thread759-1708993, as well.)

Let's go back to some fundamentals of DATE arithmetic in Oracle. Using your date values, above:

Code:
SELECT DATE '2012-12-07' - DATE '2012-10-12' Diff_in_Days FROM DUAL;

DIFF_IN_DAYS
------------
          56

select DATE '2013-01-07' - DATE '2012-12-31' Diff_in_Days FROM DUAL;

DIFF_IN_DAYS
------------
           7

Now, if we evaluate the MONTHS_BETWEEN these two sets of dates (without "+1" and without ROUND or TRUNC), we get:

Code:
SELECT MONTHS_BETWEEN (DATE '2012-12-07', DATE '2012-10-12') Diff_in_Months FROM DUAL;

DIFF_IN_MONTHS
--------------
    1.83870968

SELECT MONTHS_BETWEEN (DATE '2013-01-07', DATE '2012-12-31') Diff_in_Months FROM DUAL;

DIFF_IN_MONTHS
--------------
    .225806452

Now, reconciling the two sets of code, we see that "7 days are .225806452 of a month" and "56 days are 1.83870968 months". If you TRUNC, ROUND, or add a month into the mix, it certainly affects the results. But Oracle is doing exactly what you prescribed it to do in your code.

Did this clear things up, or did it muddy the waters?






[santa]Mufasa
(aka Dave of Sandy, Utah, USA)
“People may forget what you say, but they will never forget how you made them feel.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top