简体   繁体   中英

Conditional cumulative sum in SAS

I have been searching the solution a while, but I couldn't find any similar question in SAS in communities.

I have the following table in SAS. I need to get the cumulative value by Date . Most importantly, I need the cumulative value starts from new once it exceeds 10 .

Date            Number 
01/01/2017       3
01/01/2017       1
01/01/2017       3
01/01/2017       4
01/01/2017       6
01/01/2017       8
02/01/2017       6
02/01/2017       3
02/01/2017       5
02/01/2017       7
03/01/2017       4
03/01/2017       3 
   ...           ...

I need my output table looks like this. Just one more column shows the cumulative values.

Date            Number     cumulative
01/01/2017       3            3
01/01/2017       1            4        
01/01/2017       3            7
01/01/2017       4            4             <---- (starts from new)   
01/01/2017       6            10
01/01/2017       8            8
02/01/2017       6            6
02/01/2017       3            9
02/01/2017       5            5
02/01/2017       7            7             <---- (starts from new) 
03/01/2017       4            3
03/01/2017       3            7
   ...           ...          ...

Would someone be able to assist with this.

Thanks

Something like (untested):

data out;
  set in;
  by date; * Assumes sorted by date;
  retain cumulative;
  if first.date or cumulative+number > 10 then do;
    cumulative = 0;
  end;
  cumulative = cumulative + number;
run;

should work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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