In oracle i can find out no:of months between using MONTHS_BETWEEN function.
In postgres i am using extract function for this. eg.like
select
extract(year from age(current_date, '2012-12-09')) * 12
+
extract(month from age(current_date, '2012-12-09'))
Is there any other ways(built in functions) in postgres??
To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.
Example: Oracle MONTHS_BETWEEN () function The following statement calculates the months between two specified dates: SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE('02-02-2015','MM-DD-YYYY'), 3 TO_DATE('12-01-2014','MM-DD-YYYY') ) "Months" 4 FROM DUAL;.
This is easy to re-implement in PostgreSQL just using SQL functions to tidy up what you've already got:
create function months_of(interval)
returns int strict immutable language sql as $$
select extract(years from $1)::int * 12 + extract(month from $1)::int
$$;
create function months_between(date, date)
returns int strict immutable language sql as $$
select abs(months_of(age($1, $2)))
$$;
And now select months_between('1978-06-20', '2011-12-09')
produces 401.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With