I have a equation:
result[n] = least(0, x[n] + result[n-1])
which should produce such a table
x | result
--------------
100 | 0 // least(100+0, 0) = 0
50 | 0 // least(50+0, 0) = 0
-100 | -100 // least(-100+0, 0) = -100
50 | -50 // least(50-100, 0) = -50
I'd like to somehow use it in SQL query for table of x values. I've been thinking about lag
function like this:
select
*,
greatest(0, lag(result) over (order by i) + "table1"."value") as result
from
table1
but of course it won't work since table has no result column.
Do you have any idea how to achieve such a recursion in SQL (PostgreSQL)?