PostgreSQL Window 函数忽略空值

PostgreSQL Window Functions Ignore Null Values

我是 Postgre 的新手SQL,并且在尝试实现 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)

这个脚本 不是 return 我想要的,因为它在延迟 'looks back' 时包含空值。

提前致谢。

我想你不能只是:

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;