Question

I'm building a summary table as part of a stored procedure and I have two columns. The first column needs to show the start and the second column needs to show the end of a date range that is based from an input parameter that is a number designating the quarter. I was able to extract the following from AskTom but I have some questions.

Open C1 FOR
SELECT  ( SELECT TRUNC (SYSDATE, 'Q')-1+1 AS 'StartOf' FROM DUAL ),
SELECT  ( SELECT TRUNC(ADD_MONTHS (SYSDATE, +3), 'Q')-2 AS 'EndOf' FROM DUAL )
FROM DUAL; 

Question 1. Will the Math here account for LeapYears... I don't think it will but I'm not sure how to handle that.

Question 2. How do I add the input parameter, 'inQuarter' as the specific quarter? I've tried putting it in place of sysdate but I need to reformat it into date first I think?

Thanks in advance for any responses.

Was it helpful?

Solution

Tom Kyte has givven you the answer: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:250288900346075009

Open C1 FOR 
select add_months( dt, (inQuarter-1)*3 ),
       last_day(add_months( dt, (inQuarter-1)*3+2 ) )
from (
  select to_date( inYear || '0101', 'yyyymmdd' ) dt
  from dual)

OTHER TIPS

You can convert a numeric year and numeric quarter parameter to a DATE

SELECT add_months( trunc( to_date( to_char( <<numeric year>> ),
                                   'YYYY' ),
                          'YYYY' ),
                   3 * <<numeric quarter>> ) first_of_quarter,
       add_months( trunc( to_date( to_char( <<numeric year>> ),
                                   'YYYY' ),
                          'YYYY' ),
                   4 * <<numeric quarter>> ) - 1 last_of_quarter,
  FROM dual

The time component of both dates will be midnight on the last day of the quarter (i.e. 24 hours before the beginning of the next quarter). You may want the last of the quarter to be 23:59:59 on the last day of the quarter if you want the range to be inclusive of all possible dates in the quarter.

I suggest:

Open C1 FOR
SELECT TRUNC (d_inQuarter, 'Q') AS "StartOf",
       TRUNC(ADD_MONTHS (d_inQuarter, +3), 'Q') AS "EndOf"
FROM (SELECT add_months(to_date(to_char(i_yr)||'-01-01','YYYY-MM-DD'), (i_q-1)*3)
      AS d_inQuarter FROM DUAL); 

- with integer parameters i_yr and i_q representing the year and quarter, respectively.

Note that EndOf will represent midnight on the first day of the next quarter, so any selection should be based on conditions < "EndOf", not <= "EndOf". (This should ensure that all times on the last day of the quarter are included.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top