I have a data table that looks like this:
|Contract Date | Settlement_Prcie |
|--------------|------------------|
| 01/10/2020 | 50 |
|--------------|------------------|
| 01/11/2020 | 10 |
|--------------|------------------|
| 01/01/2021 | 20 |
|--------------|------------------|
| 01/02/2021 | 30 |
|--------------|------------------|
| 01/03/2021 | 50 |
|--------------|------------------|
I would like to write a query that sums every two rows beneath ... For example, On the first row with contract date 01/10/2020, the sum column would add 10 and 20 to give a result of 30. The next row, the sum column would add 20 and 30 to give 40 and so on. The resulting table of results would look like this:
|Contract Date | Settlement_Prcie | Sum Column |
|--------------|------------------|------------|
| 01/10/2020 | 50 | 30
|--------------|------------------|------------|
| 01/11/2020 | 10 | 50
|--------------|------------------|------------|
| 01/01/2021 | 20 | 80
|--------------|------------------|------------|
| 01/02/2021 | 30 |
|--------------|------------------|
| 01/03/2021 | 50 |
|--------------|------------------|
Could anyone please help me with the query to do this not just for 2 subsequent rows but for x subsequent rows.
So far I had tried using a SUM (Settlement_Price) Over (order by Contract_date Rows between 3 preceding and current row) - Current row
of course was not ok, but that is as far as I had gone.
You can use the
SUM
analytic function:Or you can use
LEAD
:So, for the test data:
Both queries output:
db<>fiddle here