简体   繁体   English

SAS SQL - 如何获得过去 X 个月的累计总和

[英]SAS SQL - How to get cumulative sum in past X months

I have a table like this one:我有一张这样的桌子:

表原样

I would like to calculate cumulative sum for column "total" for each cust_id in last x months, based on date_ini and today, so my output would be:我想根据 date_ini 和今天计算过去 x 个月中每个 cust_id 列“total”的累积总和,所以我的 output 将是:

期望的输出

Could you help me doing this in sas / proc sql?你能帮我在 sas / proc sql 中做这个吗?

Thanks!谢谢!

Cumulative results can be computed with SQL using a self-join with grouping and range limiting criteria.累积结果可以通过 SQL 使用具有分组和范围限制标准的自连接来计算。

Example:例子:

data have;
  call streaminit(2021);
  do id = 1 to 10;
    do date = '01jan2017'd to '31dec2020'd;
      x = rand('integer', 10);
      if rand('uniform') < 0.20 then output;
    end;
  end;
  format date date9.;
run;

proc sql;
  create table want as
  select 
    self.id,
    self.date,
    self.x,
    count(earlier.date) as date_count,
    sum(earlier.x) as x_sum_36mo
  from 
    have as self
  left join 
    have as earlier
  on
    self.id = earlier.id and
    earlier.date between self.date and intnx('month', self.date, -36)
  group by
    self.id, self.date, self.x
  ;

A DOW loop in SAS DATA step is more performant, and multiple cumulative periods can be computed during a single pass through the data. SAS DATA 步骤中的 DOW 循环性能更高,并且可以在单次遍历数据期间计算多个累积周期。 Such code can be found in earlier questions.这样的代码可以在前面的问题中找到。

It just looks like you want use CASE to decide whether the TOTAL contributes to your new sum.看起来您想使用 CASE 来决定 TOTAL 是否有助于您的新总和。

So assuming your reference date is the current date you might use something like this.因此,假设您的参考日期是当前日期,您可能会使用这样的日期。

create table want as
  select cust_id
       , sum(case
             when (date_ini >= intnx('month',today(),-1,'b') then total
             else 0 end) as total_last_month
       , sum(case
             when (date_ini >= intnx('month',today(),-36,'b') then total
             else 0 end) as total_last_36months
  from have
  group by cust_id
;

But I am not sure I would call those cumulative sums.但我不确定我是否会称这些累积总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM