PostgreSQL 的窗口函数 IGNORE NULLS 解决方法

Bru*_*omé 6 postgresql window-functions

通过以下查询,我可以使用 LAG() 函数重复列的最后一个非空值c

SELECT coalesce(open_time, extract(EPOCH from date_trunc('minute', datetime)) * 1000)               open_time,
   coalesce(o, LAG(c) over w)                                                                          o,
   coalesce(h, LAG(c) over w)                                                                          h,
   coalesce(l, LAG(c) over w)                                                                          l,
   coalesce(c, LAG(c) over w)                                                                          c,
   coalesce(v, 0)                                                                                      v,
   coalesce(close_time, extract(EPOCH from date_trunc('minute', datetime)) * 1000 + ((60000 * 1) - 1)) close_time
from temporary_timeframe 
window w as (order by datetime);
Run Code Online (Sandbox Code Playgroud)

得到以下结果:

在此处输入图片说明

但是我需要c在当前列值为空时重复列的值。我看到如果 PostgreSQL 支持IGNORE NULLS窗口函数的属性,这将得到解决。如何解决这个没有IGNORE NULLS

McN*_*ets 5

LAG() 不会重复最后一个非空值。

引用自文档

返回在分区内当前行之前偏移行的行处计算的值;如果没有这样的行,则返回默认值(必须与值的类型相同)

但是您可以根据一个列值设置一个分区,然后使用 firts_value() 函数。

create table tbl (id int, a int, b int, c int);
Run Code Online (Sandbox Code Playgroud)
?
insert into tbl values
(1, 12, 4, 3),
(2, 10, 10, 5),
(3, 6, 12, 23),
(4, 6, null, 10),
(5, 7, null, 4),
(6, 1, 8, 10),
(7, 4, null, 3);
Run Code Online (Sandbox Code Playgroud)
7 行受影响
select id, a, first_value(b) over (partition by grp) as b, c
from (
      select id, a, b, c, 
             sum(case when b is not null then 1 end) over (order by id) as grp
      from   tbl
     ) t
Run Code Online (Sandbox Code Playgroud)
身份证 | | 乙 | C
-: | -: | -: | -:
 1 | 12 | 4 | 3
 2 | 10 | 10 | 5
 3 | 6 | 12 | 23
 4 | 6 | 12 | 10
 5 | 7 | 12 | 4
 6 | 1 | 8 | 10
 7 | 4 | 8 | 3

db<>在这里摆弄