简体   繁体   中英

Dynamic variables in Oracle SQL Developer

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?

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

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, eg

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

or as an ANSI date literal:

DEFINE SALE_DT = DATE '2016-12-20'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM