I need help making a query that will return results from a table for where all people are currently 25 and whose birthdate is in 2 months (anytime of the month).
My current query is:
SELECT * from account_info
where to_char(SYSDATE,'YYYY')-to_char(birth_date,'YYYY') = 25
AND Months_between(TO_DATE(SYSDATE),TO_DATE(birth_date)) = 2
The format of birth_date in the database is 11-NOV-87
This isn't returning the proper months I need, because this is also calculating the years and it comes out to be 297 months. I was previously using:
AND abs(to_char(SYSDATE,'MM')-to_char(birth_date,'MM')) = 2`
which showed the proper result but I'm not sure if this will work if the current SYSDATE = December
and the birth_date = February
.
How do I return only the people that are currently 25 and where their birthdate is 2 months from the SYSDATE using the proper date calculations?
Try:
WHERE months_between(trunc(sysdate,'mm'),trunc(birth_date,'mm'))=310
EDIT Corrected month count from 298 to 310 (it was calculating 24 turning 25 rather than 25 turning 26).
SOLUTION:
SELECT * from account_info
WHERE to_char(SYSDATE,'YYYY')-to_char(birth_date,'YYYY') = 25 AND to_char(add_months(TRUNC(SYSDATE), 2),'MM') = to_char(birth_date,'MM');
The add_months will add 2 to the current sysdate month and compare that value to the birth_date.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.