Skip to Main Content
  • Questions
  • Setting End of Last year date when a query is run in Jan.

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, dhiraj.

Asked: June 03, 2019 - 1:13 pm UTC

Last updated: July 23, 2019 - 10:15 am UTC

Version: NA

Viewed 1000+ times

You Asked

Hi,

Hope all have started to enjoy the summer (also may be struggling with too much heat waves).

I have a question on how to construct a query where I use a date like 'End of last year' (EOLY)

I run this query once a month for the previous month data

The End of last year works fine when I run this query from Feb to Dec ( so for example, now if I run the query the EOLY will be '31/12/2018'

But when I run this in January, EOLY needs to be '31/12/2017' because I am pulling the data of last month i.e. 2018

how do I adjust the query with something like by using the sysdate?

thanks in advance
Jain

and Chris said...

I don't see your current query?

Anyway, sounds like you just want to offset your end of last year calculations by one month. Which you can do by:

- Subtracting one month from the sysdate (add_months(dt, -1))
- Finding the start of the year this date is in (trunc(dt, 'y'))
- Subtracting one day (dt-1)

alter system set fixed_date = '2019-01-01';

select trunc ( add_months ( sysdate, -1 ), 'y' ) - 1
from   dual;

TRUNC(ADD_MONTHS(SYSDATE,-1),'Y')-1   
31-DEC-2017 00:00:00

alter system set fixed_date = '2019-02-02';

select trunc ( add_months ( sysdate, -1 ), 'y' ) - 1 
from   dual;

TRUNC(ADD_MONTHS(SYSDATE,-1),'Y')-1   
31-DEC-2018 00:00:00 

alter system set fixed_date = none;

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Thank you Chris, it was a great learning experience helping and sharing information

dhiraj Jain, July 22, 2019 - 1:13 pm UTC

Thank you for your reply on this.

I couldn't get time to see the post again since I had got the solution using the SQl I was using - I just converted the same online. The result was something as below:

EXTRACT(YEAR FROM maturity_date) = EXTRACT(YEAR FROM TRUNC(SYSDATE) - INTERVAL '1' MONTH)
AND EXTRACT(MONTH FROM maturity_date) <= EXTRACT(MONTH FROM TRUNC(SYSDATE) - INTERVAL '1' MONTH)


Chris Saxon
July 23, 2019 - 10:15 am UTC

Cool, glad you got this working.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.