Skip to content
Advertisement

how do i insert value into a column and referring the previous value at the same time of that column in a Table in Oracle?

I have a table where I have to insert values in Final_value column

date      column1  column2   Final_value   
01-01-10    5.5       Null        Null
02-01-10    4.2       Null        NULL
03-01-10    5.3       0.4         NULL
04-01-10    6.4       Null        NULL
05-01-10    7.0       0.3         NULL
06-01-10    7.7       Null        NULL

Explanation of the task

  1. First value of the Final_value column will be = 1st value of column1 i.e 5.5

  2. From the 2nd row we will check if column2 is Not Null
    a) if TRUE , then formula would be
    previous Final_value column* ( current column1 value/previous Column1 value ) + column2 value * (previous column1 value/ previous Final_value )

    b) if FALSE, then formula would be the Previous value of Final_value column * ( current value of column1/ previous value of column 1)

Required Output

date      column1  column2   Final_value   
01-01-10    5.5       Null        5.5
02-01-10    4.2       Null        4.2
03-01-10    5.3       0.4         5.7
04-01-10    6.4       Null        6.883019
05-01-10    7.0       0.3         7.850943
06-01-10    7.7       Null        8.636038

Advertisement

Answer

declare
v_num integer := 1;
v_column1 number(8,2);
v_column2 number(8,2);
v_Final_value number(8,2);
begin
for rec in (select * from tab order by mydate)
loop
   if(v_num = 1) then
       
       update tab set Final_value = column1 where mydate = rec.mydate;     
   else
       if(rec.column2 is not null) then
          update tab set Final_value =
           v_Final_value * (v_column1/rec.column1) +
           rec.column2 * (v_column1/v_Final_value) where mydate = rec.mydate;
       else
          update tab set Final_value =
          v_Final_value * (rec.column1 / v_column1) where mydate = rec.mydate;
       end if;
   end if;
   
   
   v_num:= v_num +1;
   
   v_column1 := rec.column1;
   v_column2 := rec.column2;
   
   select final_value 
   into v_Final_value
   from tab
   where mydate = rec.mydate;
     
end loop;
end;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement