BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
gsisme
Obsidian | Level 7

Hi,

I'm working on a piece of data where I'm try to carry out a cumulative sum with multiple criteria. Using the table below as an example, I'm trying to sum the Amount based on the Date of each ID (I need the most recent months total Amount as an output). I generally use the Retain function for this (script below)  however I don't know how this works with more than 1 By variable. Does anyone have any suggestions? ()

 

Data have;

set want;

by ID;

Retain Amount1;

if first.ID then Amount1=Amount;

else Amount1=Amount+Amount1;

run;

 

IDDateAmount
101/02/2018-72545
101/02/2019-29457
101/03/2019-54466
101/03/2019-88336
201/06/2019-83525
201/06/201977979
201/07/201947607
201/08/2019-48059
201/03/202038094
301/02/201856534
301/09/201820874
301/03/2019-13083
301/03/201977668
301/04/2020-80950
301/04/2020-57656
1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26

I'm not sure I follow your explanation ... it sounds like you want a cumulative sum by ID and date, and when a new date is found, the cumulative sum restarts. Is that what you want? It would help if you showed us the output you want.

 

Nevertheless, if my guess is right, this is how to do it.

 

proc sort data=have;
    by id date;
run;
data want;
    set have;
    by id date;
    if first.date then cumulative_sum=0;
    cumulative_sum+amount;
run;
--
Paige Miller

View solution in original post

2 REPLIES 2
PaigeMiller
Diamond | Level 26

I'm not sure I follow your explanation ... it sounds like you want a cumulative sum by ID and date, and when a new date is found, the cumulative sum restarts. Is that what you want? It would help if you showed us the output you want.

 

Nevertheless, if my guess is right, this is how to do it.

 

proc sort data=have;
    by id date;
run;
data want;
    set have;
    by id date;
    if first.date then cumulative_sum=0;
    cumulative_sum+amount;
run;
--
Paige Miller
gsisme
Obsidian | Level 7
Hi,
Apologies if i was unclear above, however you interpreted it correctly. I've applied the solution and it's doing exactly what I need. Thank you.

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 550 views
  • 0 likes
  • 2 in conversation