I have a table with given values
| id | level | value |
| --- | ------ | ----- |
| 1 | 30000 | 0.05 |
| 2 | 100000 | 0.06 |
| 3 | 120000 | 0.07 |
I want to create an postgres sql query to get a sum in the following logic. I will be providing a value (level) as as parameter to the query (170000).
(100000- 30000)*0.05 + (120000-100000)*0.06 + (170000-120000)*0.07
(difference of level of row2 and row1) * value of row1 +
(difference of level of row3 and row2) * value of row2 +
(difference of level as input and row3) * value of row3
2
Answers
You may use
LEAD
function to get the next level value, and find the sum according to your logic as the following:See a demo.
Use
LEAD
to see the next row’s value. UseCOALESCE
to substitute the last missing value with 170000.