I am trying to convert formulas from a Google Sheet file to SQL. I get stuck on a recursive formula (calling on the result of the previous line of the same column).
Here is the table I am working with
timestamp var1
1602460890 1
1602460900 3
1602460910 4
1602460920 4
1602460930 1
1602460940 8
1602460950 2
1602460960 3
1602460970 4
1602460980 2
I wish to have the following result, with the addition of the column "var2"
timestamp var1 var2
1602460890 1
1602460900 3 1 # 1 = 1 + 3 * 0
1602460910 4 5 # 5 = 1 + 4 * 1
1602460920 4 21 # 21 = 1 + 4 * 5
1602460930 1 0 # Here the result is "0" because in the previous line, the result is greater than a threshold (the threshold is set at 10)
1602460940 8 1 # 1 = 1 + 8 * 0
1602460950 2 3 # 3 = 1 + 2 * 1
1602460960 3 10 # 10 = 1 + 3 * 3
1602460970 4 41 # 41 = 1 + 4 * 10
1602460980 2 0 # Here the result is "0" because in the previous line, the result is greater than a threshold (the threshold is set at 10)
"var2" is equal to 1 to which we add "var1" multiplied by the previous result of "var2". But if its previous result is greater than 10 (the threshold is set at 10), then the result will be zero.
The SQL query might look like this, but this one logically returns the following error:
"SYNTAX_ERROR: line 3:18: Column 'var2' cannot be resolved"
SELECT *,
(CASE
WHEN (lag(var2, 1) OVER (ORDER BY timestamp)) > 10 -- (the threshold is set at 10)
THEN 0
ELSE 1 + (var1 * (lag(var2, 1) OVER (ORDER BY timestamp))) END)
AS var2
FROM my_table
Would anyone have an idea to solve this problem or maybe I have to change SQL language? Thanks for your help