PostgreSQL IGNORE NULLS在窗口函数中

时间:2017-12-08 17:05:05

标签: sql postgresql window-functions

enter image description here

在没有IGNORE NULLS的左侧面板数据上 在IGNORE NULLS的右侧面板数据上。

所以我需要在PostgreSQL中获得正确的变体

需要在PostgreSQL中的窗口函数(LEAD和LAG)中模拟Oracle IGNORE NULLS。

SELECT empno,
   ename,
   orig_salary,
   LAG(orig_salary, 1, 0) IGNORE NULLS OVER (ORDER BY orig_salary) AS sal_prev
FROM   tbl_lead;

如果有NULL,则应返回最新的非空值。

我已经通过PostgreSQL用户定义的聚合函数尝试了它,但它很难理解它的方法https://www.postgresql.org/docs/9.6/static/sql-createaggregate.html

解决方案无法通过WITH子句或子查询实现,因为它在复杂查询中使用。

2 个答案:

答案 0 :(得分:1)

聚合有点复杂,因为您必须存储两个先前的值。可以使用数组作为state-data和最终函数来完成:

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
);

用法:

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)

答案 1 :(得分:0)

我更新了@klin的回答。下面的函数允许传递任何元素,具有偏移和默认参数。

LAG(表达式[,偏移[,默认]])

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
);

用法:

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;

enter image description here

它对我有用。 如果需要,请更正。

相关问题