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

I have a data that looks like this:

ID Count
1 3
2 1
3 2
4 12
5 3
6 2
7 9
8 11
9 3
10 7

 

I want to sum up 'Count' starting from the first row.  As soon as the Sum >= 20, the process starts over. Something looks like this:

ID Count Sum 
1 3 3
2 1 4
3 2 6
4 12 18
5 3 21
6 2 2
7 9 11
8 11 22
9 3 3
10 7 10
1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26
data want;
    set have;
    if sum>=20 then sum=0;
    sum+count;
run;
--
Paige Miller

View solution in original post

3 REPLIES 3
PaigeMiller
Diamond | Level 26
data want;
    set have;
    if sum>=20 then sum=0;
    sum+count;
run;
--
Paige Miller
ballardw
Super User

One way:

data have;
  input ID 	Count;
datalines;
1 	3
2 	1
3 	2
4 	12
5 	3
6 	2
7 	9
8 	11
9 	3
10 	7
;

data want;
   set have;
   retain runningsum;
   runningsum+count;
   output;
   if runningsum ge 20 then runningsum=0;
run;

Please note the use of a data step to provide example data. It avoids us having to ask lots of questions in some cases.

 

Retain names a variable that will hold the  value of a variable across iterations of the data step.

The "trick" here is to output the values and if you have written one greater than or equal to your target set it to 0 afterwards before used in the next total.

 

I don't like using variable names like Sum, which happens to be function, as it may confuse code and doesn't say anything about the sum of what.

sas-innovate-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 828 views
  • 3 likes
  • 3 in conversation