I have the query below where the date is hard-coded. My objective is to remove the harcoded date; the query should pull the data for the previous month when it runs.
select count(distinct switch_id)
from xx_new.xx_cti_call_details@appsread.prd.com
where dealer_name = 'XXXX'
and TRUNC(CREATION_DATE) BETWEEN '01-AUG-2012' AND '31-AUG-2012'
Should I use sysdate-15
function for that?
Modifying Ben's query little bit,
I believe this would also work:
It has the advantage of using BETWEEN which is the way the OP used his date selection criteria.
Data for last month-
Getting last nth months data retrieve
The
trunc()
function truncates a date to the specified time period; sotrunc(sysdate,'mm')
would return the beginning of the current month. You can then use theadd_months()
function to get the beginning of the previous month, something like this:As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g.
DATE 2012-08-31
, or theto_date()
function, for exampleto_date('2012-08-31','YYYY-MM-DD')
. If you don't then you are bound to get this wrong at some point.You would not use
sysdate - 15
as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not usingtrunc()
.Just as a little demonstration of what
trunc(<date>,'mm')
does: