Thursday, August 24, 2017

How do I write a SQL to display the number of months between two dates

Answer:  Here is a simple way to display all months between a range of dates, without referencing any table:
SELECT
   MOD( TRUNC( MONTHS_BETWEEN( '2015-07-29', '2015-03-28' ) ), 12 ) as MONTHS

FROM DUAL;

Here is a way to name all of the months between two dates:
select to_char(which_month, 'Mon-yyyy') month
from
(
select
add_months(to_date('01-2016','mm-yyyy'), rownum-1) which_month
from
dba_objects
where
rownum <= months_between(to_date('12-2016','mm-yyyy'), add_months(to_date('01-2016','mm-yyyy'), -1))
order by
which_month
);


MONTH
--------
Jan-2016
Feb-2016
Mar-2016
Apr-2016
May-2016
Jun-2016
Jul-2016
Aug-2016
Sep-2016
Oct-2016
Nov-2016

MONTH
--------
Dec-2016

12 rows selected.


 
Here is a script that uses the last_day function to show the number of months between two dates: 

select
   distinct(last_day(to_date(td.end_date + 1 - rownum)))

from
   all_objects,

   (-- this is just to easily substitute dates for the example...
      select to_date('30-JAN-2010') start_date
            ,to_date('15-MAR-2011') end_date
      FROM   DUAL  ) td
where
   trunc(td.end_date + 1 - rownum,'MM') >= trunc(td.start_date,'MM')

order by 1


(LAST_DAY
---------
31-JAN-10
28-FEB-10
31-MAR-10
30-APR-10
31-MAY-10
30-JUN-10
31-JUL-10

No comments:

Post a Comment

To generate a PDF using JavaScript in Oracle APEX from a collection

  To generate a PDF using JavaScript in Oracle APEX from a collection, you can follow these steps: 1. Create a button or link on your APEX p...