I'm trying to update a column by using the following procedure, it uses the LAG function as the result is calculated by subtracting the previous value to the current value as it can be seen in the image below, but it does not work so far as it populates the col3 with values that I don't expect at all..
Basically what I want is (use Excel to illustrate the problem):
And I want this for every different name in the table.
create or replace procedure proc1 as
cursor cur is
SELECT (col1 - LAG(col1,1) OVER (PARTITION BY name order by ID))
FROM table1
for update;
var_diff NUMBER;
begin
open cur;
loop
fetch cur into var_diff;
exit when cur%NOTFOUND;
update table1 set col3=var_diff where current of cur;
end loop;
close cur;
end proc1;
/
exec proc1;
commit;
I know for example that the SQL statement used above works:
SELECT col1,
LAG(col1,1) OVER (PARTITION BY name order by ID),
(col1 - LAG(col1,1) OVER (PARTITION BY name order by ID))
FROM table1;
But I cannot make the procedure work.