PostgreSQL窗口函数忽略空值

时间:2015-04-30 18:45:53

标签: postgresql lag

我对PostgreSQL比较陌生,并且在忽略空值时很难尝试实现lag()函数。根据文档http://www.postgresql.org/docs/9.4/static/functions-window.html,不可能简单地将参数传递给函数来实现此目的。

有没有人知道任何解决方法?你可以编写任何一个例子,但是如果它有帮助你可以开始:

Col_A   Col_B  Col_A_Lag  Col_B_Lag  ID  Date
VA_1    100    VA_1       100        AA  Jan-1 
null    null   VA_1       100        AA  Jan-2
null    null   VA_1       100        AA  Jan-3
VA_2    250    VA_2       250        AA  Jan-4
VA_2    300    VA_2       300        AA  Jan-5  
null    null   VA_2       300        AA  Jan-6

如果我从tbl_x开始,这是一个简单的SQL脚本:

select
Col_A,
Col_B,
case when Col_A is null then lag(Col_A) over w else Col_A end as Col_A_Lag,
case when Col_B is null then lag(Col_B) over w else Col_B end as Col_B_Lag
from tbl_x
window w as (partition by ID order by Date)

此脚本将返回我想要的内容,因为它在滞后'回溯'时包含空值。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我想你不能只是:

select
from tbl_x
window w as (partition by ID order by Date)
where col_a is null;

如果没有,那么您可能需要:

select
Col_A,
Col_B,
case when Col_A is null
  then (select col_a
          from tbl_x x2
         where x2.id = x1.id
           and col_a is not null
           and x2.date < x1.date
      order by date desc
         limit 1)
  else Col_A
  end Col_A_Lag,
case when Col_B is null
  then (select col_b
          from tbl_x x2
         where x2.id = x1.id
           and col_b is not null
           and x2.date < x1.date
      order by date desc
         limit 1)
  else Col_B
  end Col_B_Lag
from tbl_x x1;

通过适当的索引,性能可能会非常好。

create index ... (id, date desc, col_b) where col_b is not null;