turn on suggestions

Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.

Showing results for

Find a Community

- Home
- /
- SAS Programming
- /
- SAS Procedures
- /
- Sum column based on row count

Topic Options

- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

08-22-2017 02:51 PM

Hello,

I have searched all over and can't seem to find an answer for this. For each row, I am attempting to sum the values of the next x rows (3 in the example below) for each item.

Example: Item 1, row count for aggregation = 3, next 3 rows countain 10 in each row which equals a sum of 30. It only sums for the item that corresponds to the row that the sum calculation is on (similar to a group by).

The example below is far simpler than my real data which contains different values for sales for each row.

I am assuming that this would be an iterating do until loop of some sort but I can't seem to think of a strategy. Thanks for all of your insight!

Item | Sales | SumRolling |

1 | 10 | 30 |

1 | 10 | 30 |

1 | 10 | 30 |

1 | 10 | 30 |

1 | 10 | 30 |

1 | 10 | 30 |

1 | 10 | 20 |

1 | 10 | 10 |

2 | 20 | 60 |

2 | 20 | 60 |

2 | 20 | 60 |

2 | 20 | 60 |

2 | 20 | 60 |

2 | 20 | 40 |

2 | 20 | 20 |

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

08-22-2017 03:12 PM

Do you have SAS ETS? If so, a CONVERT statement is your best bet.

If not, the quickest way, IMO is to reverse the data, use the LAG function and then reverse the data order again. Assuming you can do the re-ordering yourself, here's how the data step may look.

```
data want;
by item sales;
l1=lag(sales);
l2=lag2(sales);
l3=lag3(sales);
if first.item then count=1; else count+1;
if count > 3 then do;
sum = sum(l1, l2, l3);
end;
run;
```

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

08-23-2017 08:54 AM

data have; infile cards expandtabs; input Item Sales; cards; 1 10 30 1 10 30 1 10 30 1 10 30 1 10 30 1 10 30 1 10 20 1 10 10 2 20 60 2 20 60 2 20 60 2 20 60 2 20 60 2 20 40 2 20 ; run; data have; set have; by item; if first.item then n=0; n+1; run; proc sql; select a.*,(select sum(sales) from have where item=a.item and n between a.n and a.n+2) as rolling_sum from have as a; quit;