SAS 从以前的结果中减去最近的结果

SAS subtracting the most recent results from the previous ones

我想修改函数代码以减去结果,例如今天的 Run_date 来自上一个。但是,我的观点是,它应该只减去相同 POLICY_VIntage 的结果,即当前 (rund_date) 2021.01 - 之前 (2021.01)。不像下面的图片,例如 2021.08 - 2021.09 [![在此处输入图片描述][1]][1]

我想要这样的

  [1]: https://i.stack.imgur.com/T7k8Y.png


proc sql;   
create table policy_vintage_weekly as
  select 
    policy_vintage
    ,count(NRB) as number_policy
    ,today() as Run_Date format weeku.
  from PolisyEnd
  where POLIS= "W"
  group by policy_vintage
;
quit;

data policy_vintage_weekly_all;
set
  _work.policy_vintage_weekly (where=(run_date ne today()))
  policy_vintage_weekly
;
by policy_vintage run_date;
run;

%if &syscc. = 0
%then %do;


data _work.policy_vintage_weekly;
set policy_vintage_weekly_all;
by policy_vintage;
diff_value = dif(number_policy);
if not last.policy_vintage then diff_value = .;
run;
%end;
/* print report */
proc print data=_work.policy_vintage_weekly noobs;
var policy_vintage number_policy run_date diff_value;
run;

使用SQL按保单年份加入当天的数据和最近的前一天的数据,然后将这两个值相减。

示例数据:

data have;
    input run_date:date9. policy_vintage$ total;
    format run_date date9.;

    datalines;
02NOV2021 A 100
02NOV2021 B 200
02NOV2021 C 300
;
run;

data history;
    input run_date:date9. policy_vintage$ total;
    format run_date date9.;

    datalines;
01NOV2021 A 10
01NOV2021 B 20
01NOV2021 C 30
02NOV2021 A 100
02NOV2021 B 200
02NOV2021 C 300
;
run;

解决方案:

proc sql noprint;
    create table want as
        select today.policy_vintage
             , today.total as total_today
             , prior.total as total_prior
             , today.total - prior.total as diff
        from have as today
        LEFT JOIN
             (select *
              from history
              where run_date < today()
              having run_date = max(run_date)
             ) as prior
        ON today.policy_vintage = prior.policy_vintage
   ;
quit;

输出:

policy_vintage  total_today total_yesterday diff
A               100         10              90
B               200         20              180
C               300         30              270

这只需要在每个 policy_vintage 的第一个上完成。

data _work.policy_vintage_weekly;
set policy_vintage_weekly_all;
by policy_vintage;
diff_value = dif(number_policy);
if first.policy_vintage then diff_value = .;
run;

旁白:如果您的流程有一天中断并且您需要在同一天重新运行,会发生什么情况?如果出现部分负载会怎样?