Jason Samuels
Jason Samuels

Reputation: 65

Oracle SQL - Sum next X number of Rows

I have a table in Oracle database whith projected sales per week and would like to sum the next 3 weeks for each week. Here is an example of the table for one product and what I would like to achieve in the last column.

enter image description here

I tried the Sum(Proj Sales) over (partition by Product order by Date), but I am not sure how to configure the Sum Over to get what I am looking for.

Any assistance will be much appreciated.

Upvotes: 1

Views: 691

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

You can use analytic functions. Assuming that the next three weeks are the current row and the next two:

select t.*,
       sum(proj_sales) over (partition by product
                             order by date
                             rows between current row and 2 following
                            ) as next_three_weeks
from t;

Upvotes: 1

Related Questions