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

How to calculate cumulative sum of below data using Lag function?

 

Name Marks

AA  50

BB 60

CC  70

DD 80

EE 90

FF 100

 

output should be:

Name Marks  Cumulative marks

AA    50   50

BB   60   110

CC   70  180

DD  80   260

EE  90  350

FF  100 450

1 ACCEPTED SOLUTION

Accepted Solutions
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Like any problem, it can be done, but why on earth would you want to go through that?  You would need to create a lag statement specifically for each row of data as you cannot conditionally execute lag statements, so this would not work:

data want;
  set have;
  calc_marks=lag(calc_marks)+marks;
run;

If you try it you will get all kinds of weird results as the value used in the lag (which is a queue of values) does not work conditionally.

Use retain, its what its for.

View solution in original post

5 REPLIES 5
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Use retain, its what it is for:

data want;
  set have;
  retain cumulative_marks;
  cumulative_marks=ifn(_n_=1,marks,sum(sumulative_marks,marks));
run;
aman23
Obsidian | Level 7
yes using retain can get the result, but can it be done using Lag function???
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Like any problem, it can be done, but why on earth would you want to go through that?  You would need to create a lag statement specifically for each row of data as you cannot conditionally execute lag statements, so this would not work:

data want;
  set have;
  calc_marks=lag(calc_marks)+marks;
run;

If you try it you will get all kinds of weird results as the value used in the lag (which is a queue of values) does not work conditionally.

Use retain, its what its for.

PaigeMiller
Diamond | Level 26
data want;
  set have;
  cumulative_marks+marks;
run;

You don't need anything more complicated.

--
Paige Miller
novinosrin
Tourmaline | Level 20

Hello @aman23  did this

  calc_marks=lag(calc_marks)+marks;

really work for your sample? 

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 5 replies
  • 7784 views
  • 1 like
  • 4 in conversation