[英]Dynamic variables in Oracle SQL Developer
I have four queries setup for each sale_Dt
criteria and would like to consolidate into 1 query. 我为每个
sale_Dt
条件设置了四个查询,并希望合并为1个查询。
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
. 我想将
SALE_DT
一个动态变量,该变量在sale_Dt
中循环,其值为sale_dt = 20dec2016
和sale_dt - 7
, sale_dt - 8
和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: 您可以使用
OR
或IN
子句指定日期的四个变体,例如:
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: 您还可以将整个
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;
Or us IN
to make it even shorter: 或者我们
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;
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'
. 我在
to_date()
调用中包含了NLS数据语言参数,因为您使用的字符串假定会话将理解'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: 或作为ANSI日期文字:
DEFINE SALE_DT = DATE '2016-12-20'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.