postgresql - Postgres window function output restriction -


i using postgres 9.1.11 , have created function cumulate variable (ln_ret) on partition, returning desired column (cumret_pf). parameters start_date , end_date determine how wide want relevant partition be.

my issue want result returned if there enough rows in partition, e.g. if specify partition starts 2 rows preceding current variable, want first 2 rows in partition null.

i have been able achieve code below rows preceding current row unable achieve desired result when consider rows following the current row. can calculate variable such 'inverse' row number, , perform equivalent restriction end_date have below? there better way restrict results? many thanks

select allrows.rnum,   allrows.permno,   allrows.date,   allrows.ln_ret,   allrows.sum_ln_ret,   cast(exp(allrows.sum_ln_ret) - 1 numeric(18,6)) cumret_pf    (select cast(row_number() on (partition a.permno order a.date) bigint) rnum,   a.permno,    a.date,   a.ln_ret,    sum(a.ln_ret) on (partition a.permno order a.date rows between 3 preceding , 3 following) sum_ln_ret returns.msf_mse a.ln_ret not null , permno = 10000 order a.permno, a.date) allrows rnum > 3; 

my output appears shown below (when using window of 3 rows pre/post shown in amended code). able set value of cumret_pf in final 3 rows null (or delete them alltogether, have first 3 rows). not want hard code row number full dataset has many thousand partitions of varying lengths.

rnum;permno;date;ln_ret;sum_ln_ret;cumret_pf  -------------------------------------------------- 4;10000;"1986-05-30";-0.251872;-1.386295;-0.750000 5;10000;"1986-06-30";-0.005038;-1.147884;-0.682693 6;10000;"1986-07-31";-0.084260;-1.736951;-0.823944 7;10000;"1986-08-29";-0.955512;-1.574885;-0.792969 8;10000;"1986-09-30";-0.058841;-1.796797;-0.834171 9;10000;"1986-10-31";-0.277631;-2.030170;-0.868687 10;10000;"1986-11-28";0.058269;-1.945910;-0.857143 


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -