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

Hi,

my question might be too simple but I actually have some trouble figuring it out...

what I want to do is to calculate the cumulative sum of a column, so if I have the following table:

value
10
20
30
40

I would like to add to it the following column:

cummulative sum
10
30
60
100

Thank you

1 ACCEPTED SOLUTION

Accepted Solutions
stat_sas
Ammonite | Level 13

Hi,

For many companies you need by processing. Just make sure data is sorted by company variable.

data want;

set have;

by company;

if first.company then cum_sum=0;

cum_sum+value;

run;

View solution in original post

5 REPLIES 5
Reeza
Super User

data want;

set have;

retain cum_sum;

cum_sum+value;

run;

ilikesas
Barite | Level 11

Hi Reeza,

thanks for the answer!

It is really short but I couldn't figure it out because its not so intuitive (at least to me) because I was trying to do something like setting the first cumsum to the value itself and for the rest of values to make cumsum by adding the value to the sum( ) of the previous values and I was getting a mess...

Reeza
Super User

Technically you don't even need the retain statement, the + implies the retain so the following works as well:

data want;

set have;

cum_sum+value;

run;

ilikesas
Barite | Level 11

Hi Reeza its me again,

now I would like to add another level of complexity, if I may:

assume that in the previous case I had to calculate the cumulative sum for one company, but now I need to do the same thing but for many companies, so each time I get to a new company the cumulative sum restarts calculating.

Thank you

stat_sas
Ammonite | Level 13

Hi,

For many companies you need by processing. Just make sure data is sorted by company variable.

data want;

set have;

by company;

if first.company then cum_sum=0;

cum_sum+value;

run;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to connect to databases in SAS Viya

Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 5 replies
  • 94984 views
  • 11 likes
  • 3 in conversation