2015-04-30 56 views
0

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

有谁知道任何解决方法?你可以弥补任何的例子,但如果它帮助这里是什么让你开始:

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

我想你不能只是:

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; 
+0

我很感谢您的回答,但当Col_A更改时,您的第二个解决方案无法工作。根据我如何排序'日期',我可以在Col_A_Lag中获取所有VA_1值或VA_2值。 – bsheehy

+0

啊没有发现这一点逻辑。编辑查询以包含它。 –

+0

更紧密...所有的空值都用VA_1填充....最后应该是VA_2。谢谢。 – bsheehy