I'm writing a function in PostgreSQL 9.2.
For a table of stock prices and dates, I want to calculate the percentage change from the previous day for each entry. For the earliest day of data, there won't be a previous day, so that entry can simply be Nil.
I'm aware that the WITH
statement is probably not supposed to be above the IF
statement. This is just how I've thought about it logically so far:
CREATE FUNCTION percentage_change_func(asset_histories)
RETURNS numeric LANGUAGE sql IMMUTABLE AS
$func$
DECLARE
r asset_histories%rowtype
BEGIN
WITH twodaysdata AS (SELECT date,price,asset_symbol FROM asset_histories
WHERE asset_symbol = $1.asset_symbol
AND asset_histories.date <= $1.date
ORDER BY date DESC LIMIT 2),
numberofrecords AS (SELECT count(*) FROM twodaysdata)
IF numberofrecords = 2 THEN
RETURN r.price / (r+1).price - 1 <---How do I reference r + 1??/
ELSE
RETURN NIL
ENDIF
END
$func$;
How to reference data from the next row properly?