开发者

Oracle - break dates into quarters

Given 2 dates (StartDate and EndDate), how to do i generate quarterly periods in Pl/SQ开发者_如何转开发L.

Example:

Start Date: 01-JAN-2009
End Date: 31-DEC-2009

Expected Output:

StartDate        EndDate
01-JAN-2009      31-MAR-2009
01-APR-2009      30-JUN-2009
01-JUL-2009      30-SEP-2009
01-OCT-2009      31-DEC-2009


SELECT  ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL-1) )   AS qstart
    ,   ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL) ) -1  AS qend
FROM    (   SELECT  TO_DATE('&start_date')  AS start_date
                ,   TO_DATE('&end_date')    AS end_date
            FROM    DUAL
        ) PARAM
CONNECT BY ADD_MONTHS( TRUNC(PARAM.start_date, 'Q'), 3*(LEVEL) ) -1
        <= PARAM.end_date

Rules for params, you may need to adjust the query to suit your purposes:

  • If start_date is not exact quarter start it effectively uses the quarter contain start date.
  • If end_date is not exact quarter end then we end on the quarter that ended BEFORE end_date (not the one containing end date).


Here's one way that you can do it with PL/SQL

declare
  startDate Date := '01-JAN-2009';
  endDate   Date := '31-DEC-2009';
  totalQuarters number := 0;

begin

  totalQuarters := round(months_between(endDate, startDate),0)/3;

  dbms_output.put_line ('total quarters: ' || totalQuarters);
  for i in 1..totalQuarters loop

    dbms_output.put_line('start date: '|| startDate || ' end date:' ||    add_months(startDate -1,3));
    startDate := add_months(startDate,3) ;
   end loop;

end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜