PostgreSQL IGNORE NULLS in window functions

痞子三分冷 提交于 2019-12-05 21:44:26

The aggregate is a bit complicated, because you have to store two previous values. It can be done using an array as a state-data and a final function:

create or replace function my_lag_trans_fun(numeric[], numeric)
returns numeric[] language plpgsql as $$
begin
    if $1[2] is not null then 
        $1[1]:= $1[2];
        $1[2]:= $2;
    end if;
    return $1;
end $$;

create or replace function my_lag_final_fun(numeric[])
returns numeric language sql as $$
    select $1[1];
$$;

create aggregate my_lag(numeric) (
    sfunc = my_lag_trans_fun,
    stype = numeric[],
    initcond = '{0,0}',
    finalfunc = my_lag_final_fun
);

Usage:

with my_table(name, salary) as (
values
    ('A', 100),
    ('B', 200),
    ('C', 300),
    ('D', null),
    ('E', null),
    ('F', null)
)

select 
    name, salary, 
    lag(salary, 1, 0) over (order by salary) prev_salary,
    my_lag(salary) over (order by salary) my_prev_salary
from my_table;

 name | salary | prev_salary | my_prev_salary 
------+--------+-------------+----------------
 A    |    100 |           0 |              0
 B    |    200 |         100 |            100
 C    |    300 |         200 |            200
 D    |        |         300 |            300
 E    |        |             |            300
 F    |        |             |            300
(6 rows)

I have updated @klin 's answer. Below functions allows to pass anyelement, has offset and default parameters.

LAG ( expression [, offset [, default] ] )

create or replace function swf_lag_trans(anyarray, anyelement, integer, 
anyelement)
returns anyarray language plpgsql as $$
begin
if $1 is null then
    $1:= array_fill($4, array[$3+1]);
end if;
if $1[$3+1] is not null then 
for i in 1..$3 loop
        $1[i]:= $1[i+1];
        i := i+1;
    end loop;
    $1[$3+1]:= $2;
end if;
return $1;
end $$;
create or replace function swf_lag_final(anyarray)
returns anyelement language sql as $$
select $1[1];
$$;
create aggregate swf_lag(anyelement, integer, anyelement) (
sfunc = swf_lag_trans,
stype = anyarray,
finalfunc = swf_lag_final
);

And usage:

with my_table(name, salary) as (
values
    ('A', 100),
    ('B', 200),
    ('C', 300),
    ('D', null),
    ('E', null),
    ('F', null)
)

select 
    name, salary, 
    lag(salary, 2, 123) over (order by salary) prev_salary,
    swf_lag(salary, 2, 123)  over (order by salary) my_prev_salary
from my_table;

It works for me. Please, correct, if required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!