PROC SQL subquery/correlated 查询
PROC SQL subquery/correlated query
pro sql number;
create table daily_total as
select distinct trans_dt,
sum((select (quantity * unit_price)
from transaction_detail
where subcat_num = 1111 and trans_dt = a.trans_dt))
from transaction_detail as a
where trans_dt between '2015-01-01' and '2015-01-02';
quit;
我知道我可以通过 group by 实现相同的目的,但我想通过子查询来实现这一点以获取学习经验。
我基本上想要 select 两个不同的日期和 return 该特定日期子类别的每笔交易的总和。
谢谢。
在 SQL 中,SUM、AVG、MAX、MIN 等聚合函数(取决于 SQL 引擎)不会 运行 子查询本身。
考虑在子查询内部使用 SUM 的以下调整。此外,我假设您希望子查询的日期范围对应于外部查询的日期和未来的某一天。因此,我使用 SAS 的 INTNX() 函数。
pro sql;
create table daily_total as
select distinct a.trans_dt,
(select sum(b.quantity * b.unit_price)
from transaction_detail As b
where b.subcat_num = 1111
and (b.trans_dt between a.trans_dt
and intnx('day', a.trans_dt, 1)) As transaction_sum
from transaction_detail a;
quit;
pro sql number;
create table daily_total as
select distinct trans_dt,
sum((select (quantity * unit_price)
from transaction_detail
where subcat_num = 1111 and trans_dt = a.trans_dt))
from transaction_detail as a
where trans_dt between '2015-01-01' and '2015-01-02';
quit;
我知道我可以通过 group by 实现相同的目的,但我想通过子查询来实现这一点以获取学习经验。
我基本上想要 select 两个不同的日期和 return 该特定日期子类别的每笔交易的总和。
谢谢。
在 SQL 中,SUM、AVG、MAX、MIN 等聚合函数(取决于 SQL 引擎)不会 运行 子查询本身。
考虑在子查询内部使用 SUM 的以下调整。此外,我假设您希望子查询的日期范围对应于外部查询的日期和未来的某一天。因此,我使用 SAS 的 INTNX() 函数。
pro sql;
create table daily_total as
select distinct a.trans_dt,
(select sum(b.quantity * b.unit_price)
from transaction_detail As b
where b.subcat_num = 1111
and (b.trans_dt between a.trans_dt
and intnx('day', a.trans_dt, 1)) As transaction_sum
from transaction_detail a;
quit;