Most data models are lacking in a good DATE Dimension and thus force developers and report developers to rely on date arithmetic to find date boundaries that are relevant to the business model. (Fiscal Year, Fiscal Quarter, Fiscal Period, Calendar Quarter, etc.) A good CALENDAR table would go a long way to making your life easier.
A simple EventDate BETWEEN SYSDATE - 458 and SYSDATE risks truncating dates out of your oldest quarter. Take TODAY as an example: SYSDATE - 458 yields 2010-09-28. If my math is correct the 3rd Quarter of 2010 started on July 1, 2010.
You need roughly 548 days to make sure you are covering the entire range of current quarter plus the previous four full quarters. Trouble is that when you this will cause some overlap as your current quarter is partially complete. So you are faced with some additional logic to truncate out the fifth oldest quarter that you don't wish to include.
My PL/SQL isn't the sharpest right now to write that logic but I hope the explanation helps shed some light on the approach you will need to take.
SELECT
FROM Events
WHERE EventDate BETWEEN SYSDATE - 548 AND SYSDATE
AND TO_CHAR(EventDate, 'Q') >=
CASE WHEN TO_CHAR(SYSDATE, 'Q') = 4
THEN 3
WHEN TO_CHAR(SYSDATE,'Q') = 3
THEN 2 WHEN TO_CHAR(SYSDATE, 'Q') = 2
THEN 1 WHEN TO_CHAR(SYSDATE 'Q') = 1 THEN 4
END
AND /* Have to handle calendar year as well */
Hope this helps.
where eventdate between sysdate - 458 and sysdate– a_horse_with_no_name Dec 30 '11 at 13:39