0

I have four queries setup for each sale_Dt criteria and would like to consolidate into 1 query.

DEFINE SALE_DT = 20DEC2016;

Select 
STORE_ID,
SALES_FINAL_DT, 
SUM(SALES) AS TOTAL_sALE
From SALES_DB
Where SALES_FINAL_DT  = '&SALE_DT'
GROUP BY STORE_ID, SALES_FINAL_DT

I would like to make SALE_DT a dynamic variable that loops through sale_Dt for values sale_dt = 20dec2016 and sale_dt - 7, sale_dt - 8 and sale_dt - 30.

I will specify the sale date in the query.

Any suggestions?

1 Answer 1

2

You can use OR or an IN clause to specify the four variations on the date, e.g:

DEFINE SALE_DT = 20DEC2016;

select STORE_ID, SALES_FINAL_DT, SUM(SALES) AS TOTAL_SALE
from SALES_DB
where SALES_FINAL_DT = TO_DATE('&SALE_DT', 'DDMONYYYY', 'NLS_DATE_LANGUAGE=ENGLISH')
or SALES_FINAL_DT = TO_DATE('&SALE_DT', 'DDMONYYYY', 'NLS_DATE_LANGUAGE=ENGLISH') - 7
or SALES_FINAL_DT = TO_DATE('&SALE_DT', 'DDMONYYYY', 'NLS_DATE_LANGUAGE=ENGLISH') - 8
or SALES_FINAL_DT = TO_DATE('&SALE_DT', 'DDMONYYYY', 'NLS_DATE_LANGUAGE=ENGLISH') - 30
group by STORE_ID, SALES_FINAL_DT;

You can also make the entire to_date() expression the substitution variable to simplify it slightly:

DEFINE SALE_DT = TO_DATE('20DEC2016', 'DDMONYYYY', 'NLS_DATE_LANGUAGE=ENGLISH')

select STORE_ID, SALES_FINAL_DT, SUM(SALES) AS TOTAL_SALE
from SALES_DB
where SALES_FINAL_DT = &SALE_DT
or SALES_FINAL_DT = &SALE_DT - 7
or SALES_FINAL_DT = &SALE_DT - 8
or SALES_FINAL_DT = &SALE_DT - 30
group by STORE_ID, SALES_FINAL_DT;

Or us IN to make it even shorter:

select STORE_ID, SALES_FINAL_DT, SUM(SALES) AS TOTAL_SALE
from SALES_DB
where SALES_FINAL_DT in (&SALE_DT, &SALE_DT - 7, &SALE_DT - 8, &SALE_DT - 30)
group by STORE_ID, SALES_FINAL_DT;

I've included the NLS data language parameter in the to_date() calls because you're using a string which assumes the session will understand 'DEC'. If you use a numeric format you don't need to do that, e.g.

DEFINE SALE_DT = TO_DATE('2016-12-20', 'YYYY-MM-DD')

or as an ANSI date literal:

DEFINE SALE_DT = DATE '2016-12-20'
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Alex, this is super helpful. Just out of curiosity, how would one deal with this if there were several (&SALE_DT - number) other than listing them in a where clause / using OR operator? How would I use a loop to do that? ...
@Aussie_Stats - Using a loop doesn't really make sense. You'd have to use PL/SQL and then combine the result sets somehow (via a collection). It would be awkward and inefficient. You could, I suppose, use an inline view or CTE to generate the various offsets and then join that to your real table, but I'm not sure it would gain you much.
Thanks, very helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.