Study guide
4.4 Accumulating Totals & Subtotals (RETAIN & Sum Statement)
SAS Certified Specialist: Base Programming Using SAS 9.4 A00-231
Track your progress as you read
Finished sections get a check mark.
1 Chapter 1: SAS Base Programming Exam Overview
1.1 A00-231 Exam Format, Scoring & Test-Day Logistics 1.2 Official Content Areas, Weights & Study Plan
2 Chapter 2: Accessing & Creating SAS Data Structures
2.1 SAS Environment, Syntax Rules, & Data Step Basics 2.2 SAS Data Libraries & the LIBNAME Statement 2.3 Investigating Libraries with PROC CONTENTS & PROC DATASETS 2.4 Importing Delimited & Excel Data with PROC IMPORT 2.5 Raw Data Ingestion with INFILE and INPUT Statements
3 Chapter 3: Managing & Combining SAS Data Sets
3.1 Reading SAS Data Sets with the SET Statement 3.2 Combining Data Sets: Concatenating & Interleaving 3.3 Match-Merging with BY Statements & FIRST./LAST. Processing 3.4 Controlling Data Output & Variable Selection (KEEP, DROP, RENAME, OBS=)
4 Chapter 4: Data Transformation & Conditional Logic
4.1 Creating & Modifying Variables with Assignment Statements 4.2 Modifying Variable Attributes with LENGTH, LABEL, FORMAT & RENAME= 4.3 Conditional Processing: IF-THEN/ELSE Statements & WHERE Subsetting 4.4 Accumulating Totals & Subtotals (RETAIN & Sum Statement) 4.5 Processing Data Iteratively with DO Loops
5 Chapter 5: SAS Functions & Data Type Conversions
5.1 Character Functions for String Manipulation 5.2 Numeric & Mathematical Functions 5.3 Working with SAS Dates, Times, & Intervals 5.4 Reading & Displaying Dates with Informats and Formats 5.5 Explicit & Implicit Data Type Conversions (INPUT & PUT)
6 Chapter 6: Restructuring Data & Program Maintenance
6.1 SAS Array Processing for Multi-Variable Transformations 6.2 Sorting Data Sets with PROC SORT 6.3 Restructuring Data Sets with PROC TRANSPOSE 6.4 Creating & Applying Custom Formats with PROC FORMAT 6.5 Simplifying Programs with Macro Variables (%LET)
7 Chapter 7: Error Handling & Debugging SAS Programs
7.1 SAS Log Analysis & Diagnostic Messages 7.2 Syntax vs. Logic Errors & Phasing 7.3 Debugging Techniques with _ERROR_, _N_, & PUT Statements 7.4 Identifying Logic Errors with the PUTLOG Statement 7.5 Handling Missing Values & Preventing Calculation Propagations
8 Chapter 8: Summary & Detail Data Reporting
8.1 Detail Reporting with PROC PRINT 8.2 Descriptive Statistics with PROC MEANS & PROC SUMMARY 8.3 Frequency & Categorical Analysis with PROC FREQ 8.4 Screening Extreme & Missing Values with PROC UNIVARIATE 8.5 Custom Tabular Reports with PROC REPORT & PROC TABULATE
9 Chapter 9: ODS Output Delivery & Data Export
9.1 Output Delivery System (ODS) Architecture Basics 9.2 Generating PDF, HTML, & RTF Output Destinations 9.3 Exporting Reports to Excel with ODS EXCEL & XLSX 9.4 Generating CSV, PowerPoint & Other ODS Destinations 9.5 Customizing ODS Titles, Footnotes, & Global Options 9.6 Exporting SAS Data Sets with PROC EXPORT & the XLSX Engine
4.4 Accumulating Totals & Subtotals (RETAIN & Sum Statement)
Key Takeaways Explain This Topic AI
At the beginning of each DATA step execution loop, SAS automatically re-initializes all newly created variables in the PDV to missing values.
The RETAIN statement overrides default re-initialization, instructing SAS to preserve a variable's stored value in the PDV across DATA step iterations.
A Sum Statement (variable + expression;) implicitly retains the target variable, initializes its value to 0 before the first iteration, and automatically ignores missing values in the expression.
Explicit accumulation (Total = Total + Amount; with RETAIN Total 0;) will convert Total to missing (.) if Amount is missing, disrupting calculations for all subsequent rows.
BY-group processing combined with FIRST.variable and LAST.variable automatic temporary variables enables resetting accumulators at group boundaries and writing subtotal rows.
Last updated: August 2026
4.4 Accumulating Totals & Subtotals (RETAIN & Sum Statement)
Quick Answer: By default, at the start of each DATA step iteration, SAS resets all non-dataset variables in the Program Data Vector (PDV) to missing ( . for numeric, blank for character). To accumulate running totals or preserve values across rows, you must prevent SAS from re-initializing variables. You can achieve this using either an explicit RETAIN statement or an implicit Sum Statement ( variable + expression; ).
Default DATA Step Re-initialization
To understand accumulation, you must understand the PDV lifecycle:
Input Variables (read via SET , MERGE , MODIFY , or INPUT ): Retain their values as new rows are read.
Created Variables (computed via assignment statements): Reset to missing at the top of every DATA step iteration loop. /* FAILS TO ACCUMULATE: RunningTotal resets to missing at the start of every row! */
- data work.bad_accumulator;
- set work.transactions;
- RunningTotal = RunningTotal + Amount; /* Always evaluates to missing (.) */
- run;
In work.bad_accumulator , RunningTotal starts as missing ( . ). On row 1, . + Amount evaluates to missing. On row 2, SAS resets RunningTotal back to missing before executing the assignment, failing to accumulate.
The RETAIN Statement
The RETAIN statement is a compile-time directive that tells SAS not to set specified variables to missing at the beginning of each execution iteration. Instead, variables keep their previous values until new values are assigned.
Syntax RETAIN variable-1 <initial-value-1> ... variable-n <initial-value-n>;
Without Initial Value : Numeric variables initialize to numeric missing ( . ), and character variables initialize to blank ( ' ' ).
With Initial Value : The variable is set to the specified constant before the first observation is processed. data work.retained_total;
set work.transactions;
- /* Preserve RunningTotal across rows, starting at 0 */
- retain RunningTotal 0;
- /* Explicit accumulator assignment using SUM function to ignore missing Amount values */
- RunningTotal = sum(RunningTotal, Amount);
- run;
- The SAS Sum Statement
SAS provides a special abbreviated syntax designed specifically for accumulation called the Sum Statement : variable + expression;
CRITICAL EXAM CONCEPT: Notice there is no equal sign ( = ) in a Sum Statement! Total + Sales; is a Sum Statement, whereas Total = Total + Sales; is an assignment statement.
The Four Implicit Behaviors of a Sum Statement
When SAS compiles a Sum Statement ( variable + expression; ), it automatically applies four rules:
Implicit Creation : Creates variable as a numeric variable if it does not already exist.
Implicit Initial Value : Sets variable initial value to 0 before processing the first observation.
Implicit RETAIN : Retains variable across all DATA step iterations.
Missing Value Immunity : Adds the value of expression to variable , treating missing values in expression as 0 (ignoring missing values). data work.sum_statement_demo;
set work.transactions;
- /* Replaces RETAIN, assignment, and SUM function in one concise statement */
- RunningTotal + Amount;
- run;
- Comparison: Explicit Retention vs. Sum Statement
Feature / Behavior Explicit Assignment ( Total = Total + Amount; with RETAIN Total 0; ) SAS Sum Statement ( Total + Amount; )
Syntax Requires RETAIN statement + Total = Total + Amount; Total + Amount; (No RETAIN , no = )
Default Initial Value Missing ( . ) unless explicitly specified in RETAIN Total 0; Automatically initialized to 0
Handling Missing Amount Evaluates to missing ( . ), corrupting Total for all subsequent rows! Treats missing Amount as 0 , preserving running total
SAS Log Behavior on Missing Writes diagnostic note: Missing values were generated... Silent execution; no log warnings
Recommended Use Case When custom initial values (e.g., 100) or complex logic are needed Standard running totals and BY-group subtotals
BY-Group Subtotal Accumulation ( FIRST. and LAST. )
In business reporting, you often need to calculate running totals per category (e.g., total sales per Department or Customer). This requires combining BY group processing with accumulation logic.
Automatic Variables: FIRST.variable and LAST.variable
When a BY statement is included in a DATA step, SAS creates two temporary automatic numeric variables for each BY variable:
FIRST.variable : Equals 1 on the first observation of a BY group, and 0 for all subsequent observations in that group.
LAST.variable : Equals 1 on the last observation of a BY group, and 0 for all other observations in that group.
Note: Input datasets MUST be pre-sorted by the BY variable (using PROC SORT ) before executing BY-group processing in a DATA step.
- Subtotal Reset Pattern /* Step 1: Pre-sort input data */
- proc sort data=sashelp.shoes out=work.shoes_sorted;
- by Region;
- run;
- /* Step 2: Accumulate subtotals per Region */
- data work.region_subtotals;
- set work.shoes_sorted;
- by Region;
- /* Reset accumulator on the FIRST row of each Region group */
- if First.Region then RegionSales = 0;
- /* Accumulate sales for rows within the Region */
- RegionSales + Sales;
- /* Subset: Output ONLY the LAST row of each Region group containing final subtotal */
- if Last.Region;
- keep Region RegionSales;
- run;
- Step-by-Step Execution Trace
When Region changes to 'Asia' , First.Region is 1. SAS sets RegionSales = 0 .
RegionSales + Sales; adds the current row's sales.
Intermediate rows ( First.Region = 0 , Last.Region = 0 ) accumulate sales without outputting because if Last.Region; filters them out.
On the final row of 'Asia' , Last.Region is 1. The subsetting IF evaluates to true, and SAS outputs the summary record containing Region and the accumulated RegionSales subtotal.