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
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.
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;
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.
data want;
set have;
cumulative_marks+marks;
run;
You don't need anything more complicated.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.