Skip to content
Advertisement

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.

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement