I got a temporary view in PostgreSQL which offers the following data (simplified):
temporary_view (sum, rw):
|sum | rw|
|1337 | 1|
|42 | 2|
|... | ...|
Now I need to do a recursion on this until my condition is reached.
For simplicity, let's say I want to calculate, how many rows I need to get a sum > 2000
.
In my real implementation I need to use a far more complicated formula.
If the sum > 2000
is reached, the recursion should stop and return the last row_number used for the calculation.
How would you implement this in SQL? I tried a lot of things but unfortunately I fail every time.
My thoughts: I would use a temporary view with (sum, row, last_row)
where I decrement last_row every time but unfortunately I'm struggling with the implementation ...
Use analytic functions to calculate a cumulative sum then get the min rw. You don't even need a recursion here.
Recursive variant for sum (you can change it on your expression):
http://sqlfiddle.com/#!12/11583/3