Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL: Calculate value using previous row

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?

like image 839
Huu Vinh Nguyen Avatar asked Oct 26 '25 20:10

Huu Vinh Nguyen


1 Answers

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
like image 50
Mureinik Avatar answered Oct 29 '25 13:10

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!