I have a table with two columns: Cur_value and Difference
       Cur_value        Difference
(-3)       3    
(-2)       4    
(-1)       5    
(1)                        1
(2)                       -2
(3)                        3
(4)     
(5)     
(6)     
(7)     
Now I want to caculate value of Cur_value from row (1) to row (7) so that
cur_value(t) = cur_value(t-3) + dif(t).
It means my result is:
           Value        Difference
(-3)           3    
(-2)           4    
(-1)           5    
(1)        3 + 1           1
(2)        4 - 2          -2
(3)        5 + 3           3
(4)    3 + 1 + 2           2
(5)    4 - 2 + 1           1
(6)    5 + 3 - 2          -2
(7) 3 + 1 + 2 - 1         -1
. My question is: how to do this action by single Oracle SQL statements?
Note that database table don't have any intrinsic order. Assuming you have some id or other column you can use to define the rows' order, you could use the lag function to get the t-3 record:
SELECT cur_value, 
       difference, 
       LAG(cur_value, 3, 0) OVER (ORDER BY id) + difference AS new_cur_value
FROM   my_table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With