Home » How to Calculate the Sum by Group in SAS

How to Calculate the Sum by Group in SAS

by Erma Khan

You can use the following methods to calculate the sum of values by group in SAS:

Method 1: Calculate Sum by One Group

proc sql;
    select var1, sum(var2) as sum_var2
    from my_data
    group by var1;
quit;

Method 2: Calculate Sum by Multiple Groups

proc sql;
    select var1, var2, sum(var3) as sum_var3
    from my_data
    group by var1, var2;
quit;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data my_data;
    input team $ position $ points;
    datalines;
A Guard 15
A Guard 12
A Guard 29
A Forward 13
A Forward 9
A Forward 16
B Guard 25
B Guard 20
B Guard 34
B Forward 19
B Forward 3
B Forward 8
;
run;

/*view dataset*/
proc print data=my_data;

Example 1: Calculate Sum by One Group

The following code shows how to calculate the sum of points by team:

/*calculate sum of points by team*/
proc sql;
    select team, sum(points) as sum_points
    from my_data
    group by team;
quit;

From the output we can see that players on team A scored a total of 94 points and players on team B scored a total of 109 points.

Example 2: Calculate Sum by Multiple Groups

The following code shows how to calculate the sum of points, group by team and position:

/*calculate sum of points by team, grouped by team and position*/
proc sql;
    select team, position, sum(points) as sum_points
    from my_data
    group by team, position;
quit;

The resulting table shows the sum of points scored by players based on their team and position.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Normalize Data in SAS
How to Rename Variables in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Related Posts