When i is greater than or equal to 3, I am trying to fetch the previous row value of that column and trying to use it in the current row calculation and I have tried using Lag function to do so but was not successful,was getting the error as "cannot use window function in UPDATE". Could some one help me out.Thanks!
CREATE OR REPLACE FUNCTION vin_calc() RETURNS text AS
$BODY$
DECLARE
r res%rowtype;
i integer default 0;
x text;
curs2 CURSOR FOR SELECT * FROM res;
BEGIN
open curs2;
-- FOR r IN curs2
LOOP
FETCH curs2 INTO r;
exit when not found;
if(x!=r.prod_grp_nm) then
i:=0;
end if;
i:= i+1;
if (i=1) then
update res set duration =0 where
dur=r.dur and prod_grp_nm=r.prod_grp_nm and week_end=r.week_end;
elsif(i=2) then
update res set duration =1 where
dur=r.dur and prod_grp_nm=r.prod_grp_nm and week_end=r.week_end;
elsif(i>=3) then
update res set gwma_duration =0.875*lag(res.duration,1) over()+(0.125*r.dur) where
dur=r.dur and prod_grp_nm=r.prod_grp_nm and week_end=r.week_end;
end if ;
x:=r.prod_grp_nm;
END LOOP;
RETURN 'yes';
END
$BODY$
LANGUAGE 'plpgsql' ;