SAS Proc SQL VERY SLOW



我有三个表:

  • 包含每个 id、年份和月份profit的主表;
  • 包含每个 id、年份和月份tax_a的表;
  • 包含每个 id、年份和月份tax_b的表。

profit已经按ID,年份和月份累积,但税收不是。我尝试使用下面的解决方案来做到这一点,它可以工作,但它非常慢。如何更有效地处理此问题?

proc sql;    
create table final_table as    
select t1.id, t1.year, t1.month, t1.profit,         
(select sum(t2.tax_a) from work.table_tax_a t2     
where ((t2.year = t1.year and t2.month <= t1.month) or (t2.year < t1.year)) and t2.id = t1.id) as tax_a,    
(select sum(t3.tax_b) from work.table_tax_b t3      
where ((t3.year = t1.year and t3.month <= t1.month) or (t3.year < t1.year)) and t3.id = t1.id) as tax_b     
from work.main_table t1;    
quit;

这很慢,因为您要为main_table中的每一行运行 2 个求和。如果可以将其从联接中拉出并放入临时表中,则可以使其运行得更快。

您的内部查询只是为每个 ID 随时间推移创建税的累积总和。

select sum(t2.tax_a) 
from work.table_tax_a t2     
where ((t2.year = t1.year and t2.month <= t1.month) or (t2.year < t1.year)) 
and t2.id = t1.id

(t2.year < t1.year)意味着您正在跨年进行此总计。 如果这是您的原因,请计算 SQL 外部的累积总和并重新连接结果。

假设您的表已按by id year month排序

data temp_a;
set table_tax_a;
by id;
retain c_tax_a;
if first.id then c_tax_a = 0;
c_tax_a = c_tax_a + tax_a;
run;

这样做是为了table_tax_b创建temp_b。 然后在 SQL 中加入它们;

proc sql noprint;
create table final_table2 as 
select t1.id, t1.year, t1.month, t1.profit, t2.c_tax_a as tax_a, t3.c_tax_b as tax_b
from main_table as t1,
temp_a as t2,
temp_b as t3
where t1.id = t2.id
and t2.id = t3.id
and t1.month = t2.month
and t2.month = t3.month
and t1.year = t2.year
and t2.year = t3.year;
quit;

某些测试数据显示的结果与您的方法相同。 我的 SQL 步骤需要 0.03 秒,你的步骤需要 0.65 秒。

最新更新