Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find First and Last Day of the last Quarter in ORACLE

Tags:

date

sql

I have a query of the form:

select *
from X
where <some_date is in the last quarter>

I'm really having trouble with getting the correct dates for the last quarter. So, say current date is 1st of July, i.e. in the third quarter, I'd like to get the 1st of April as FIRST and the 30th of June as the LAST day of the last quarter (i.e the second quarter).

Googled a bit and found tons of solutions on this, but each and every one of them covered SQL Server and the funky methods which are available there are not available on our ORACLE database (Oracle 10g and 11g).

Oh yeah, and also I need to be able to put the whole thing into one query, as that is a restriction put upon me by some tool that will further work with this query... :/

like image 944
fgysin Avatar asked Sep 08 '11 12:09

fgysin


People also ask

How do you get the first and last day of the previous month in Oracle?

Start with today's date using sysdate (3/27) and subtracts one month (2/27). We then Truncate the result using MM for the numerical value of the month(2). This will represent the first day of last month (2/1). The second manipulation requires the use of LAST_DAY instead of TRUNC.

How do I get last quarter in SQL?

For instance if the current quarter is "202201" then previous quarter should be "202104", or if the current current quarter is "202103" then previous quarter should be "202102" etc.

What is query to fetch last day of previous month in Oracle?

Oracle SQL Date Functions (Note: SYSDATE accepts no parameters.) LAST_DAY() — Returns the last day of the month for the provided date parameter.


2 Answers

This one is simpler, but may still be not the simplest way:

SELECT
  ADD_MONTHS(TRUNC(SYSDATE, 'Q'), -3) AS First,
  TRUNC(SYSDATE, 'Q') - 1 AS Last
FROM DUAL

Maybe you could also use a subselect, like this, to exclude some repetition of code:

SELECT
  ADD_MONTHS(D, -3) AS First,
  D - 1 AS Last
FROM (SELECT TRUNC(SYSDATE, 'Q') AS D FROM DUAL)
like image 104
Andriy M Avatar answered Sep 28 '22 03:09

Andriy M


SELECT
  TRUNC(SYSDATE, 'Q')AS FIRST_DAY,
  last_day(add_months(TRUNC(SYSDATE, 'Q'),2)) as LAST_DAY                
FROM DUAL;
like image 32
Ganesh C Avatar answered Sep 28 '22 03:09

Ganesh C