BookmarkSubscribeRSS Feed
MelissaWillKill
Calcite | Level 5

I am working in PROC SQL to obtain a cumulative sum.  My code currently reads:

PROC SQL;

  CREATE TABLE WorkingFile2 AS

  SELECT *,

              (SELECT SUM(B.value)

              FROM WorkingFile1 AS B

              WHERE B.ID = A.ID

              AND MDY(B.MONTH, 1, B.YEAR) <= MDY(A.MONTH, 1, A.YEAR)) AS SUM

FROM WorkingFile1 AS A
ORDER BY A.ID, A.YEAR, A.MONTH;

QUIT;

I would like for the cumulative sum to restart when it reaches a positive value.

IDYearMonthValueSumDesired Sum
1234520135

-94.32

-94.32-94.32
123452013619.82-74.5-74.5
123452013755.49-19.01-19.01
123452013828.739.729.72
1234520139-24.6-14.88-24.6
12345201310-36.4-51.28-61

How can I obtain the desired sum?  This requires the cumulative sum to reset based upon its current value. 

1 REPLY 1
PGStats
Opal | Level 21

SQL is not the proper tool to do sequential operations such as cumulative sums. Use a datastep instead, it will be simpler and much faster.

data have;

input ID  Year    Month   Value;

datalines;

12345   2013    5   -94.32

12345   2013    6   19.82  

12345   2013    7   55.49  

12345   2013    8   28.73  

12345   2013    9   -24.6  

12345   2013    10  -36.4

;

proc sort data=have; by id year month; run;

data want;

set have; by id;

if first.id or sum>0 then sum=0;

sum + value;

run;

proc print data=want noobs; run;

PG

PG

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 1 reply
  • 3772 views
  • 2 likes
  • 2 in conversation