I have to calculate my products stock cost, so for every product after each buy, i have to recalculate the Weighted Average Cost.
I got a view thats
Here what i did using function:
CREATE TYPE stock_table_with_wac AS
(document_type character varying,
document_date date,
product_id bigint,
qty_out double precision,
qty_in double precision,
price double precision,
row_num bigint,
stock_balance double precision,
wac double precision);
CREATE OR REPLACE FUNCTION calculate_wac_value()
RETURNS SETOF stock_table_with_wac AS
$BODY$
DECLARE
r_article stock_table_with_wac%rowtype;--maintain the liste of all products with there wac's value
r_in_out_article stock_table_with_wac%rowtype;--Each other records
BEGIN
--For each products
FOR r_article IN SELECT *, price FROM stock_table where document_type='SI' order by row_num
LOOP
return next r_article;
FOR r_in_out_article IN SELECT * FROM stock_table where document_type<>'SI' and product_id=r_article.product_id order by row_num
LOOP
--If there is an entry calculate the wac
if r_in_out_article.qty_in >0 then
r_in_out_article.wac:=((r_article.price * (r_in_out_article.stock_balance - r_in_out_article.qty_in)) + (r_in_out_article.qty_in * r_in_out_article.price))/(r_in_out_article.stock_balance);
--Update the wac value of the product
r_article.price:= r_in_out_article.wac;
else --The waca value still inchanged:
r_in_out_article.wac:= r_article.price;
end if;
RETURN NEXT r_in_out_article; -- return current row with caluculated wac if any
END LOOP;
return next r_article;
END LOOP;
RETURN;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION calculate_wac_value()
OWNER TO postgres;
select * from calculate_wac_value();
It seems to have a correct output. Is it a good idea to process like this?