Oracle SQL Developer中的动态变量

时间:2017-02-07 16:52:02

标签: sql oracle oracle-sqldeveloper

我为每个sale_Dt条件设置了四个查询,并希望合并为一个查询。

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

我想让SALE_DT成为一个动态变量,为sale_Dtsale_dt = 20dec2016sale_dt - 7sale_dt - 8循环sale_dt - 30

我将在查询中指定销售日期。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以使用ORIN子句指定日期的四种变体,例如:

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;

您还可以使整个to_date()表达式成为替换变量,以便稍微简化它:

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;

或我们IN让它更短:

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;

我已在to_date()次调用中包含NLS数据语言参数,因为您使用的字符串假定会话将理解'DEC'。如果您使用数字格式,则不需要这样做,例如

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

或作为ANSI日期文字:

DEFINE SALE_DT = DATE '2016-12-20'