Sum Statement

Adds the result of an expression to an accumulator variable.

Valid in: DATA step
Categories: Action
CAS
Type: Executable
Example:
data Table2;
   set Table1;
   total + x;
run;

Syntax

Arguments

variable

specifies the name of the accumulator variable, which contains a numeric value.

Tips The variable is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement.
To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value.

expression

is any SAS expression.

Tips The expression is evaluated and the result added to the accumulator variable.
SAS treats an expression that produces a missing value as zero.

Comparisons

The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:

retain variable 0;
variable=sum(variable,expression);

Example

Here are examples of sum statements that illustrate various expressions. The accumulator variable is highlighted in each example:

  • data Table2;
       set Table;
       Total + x; 
    run;
    
  • data AccountBal;
       set Account;
       retain Balance 1000;
       Balance + (-Debit);  
    run;
  • data Table2;
       set Table;
       SumXsq + x * x;
    run;
    
  • data Table2;
       set Table;
       nx + (x ne .);
    run;
    
  • data AccountBal2;
       set AccountBal;
       if Balance <=500 then Alert + 1;
    run;
    

See Also

Last updated: June 17, 2025