我知道有人问过这个问题,但为什么下面的解决方案不起作用?我想用 idx
排序的最后一个非空值填充 value
。
我看到的:
idx | coalesce
-----+----------
1 | 2
2 | 4
3 |
4 |
5 | 10
(5 rows)
我想要的:
idx | coalesce
-----+----------
1 | 2
2 | 4
3 | 4
4 | 4
5 | 10
(5 rows)
代码:
with base as (
select 1 as idx
, 2 as value
union
select 2 as idx
, 4 as value
union
select 3 as idx
, null as value
union
select 4 as idx
, null as value
union
select 5 as idx
, 10 as value
)
select idx
, coalesce(value
, last_value(value) over (order by case when value is null then -1
else idx
end))
from base
order by idx
最佳答案
你想要的是lag(ignore nulls)
。这是使用两个窗口函数执行所需操作的一种方法。第一个定义 NULL
值的分组,第二个分配值:
select idx, value, coalesce(value, max(value) over (partition by grp))
from (select b.*, count(value) over (order by idx) as grp
from base b
) b
order by idx;
您也可以通过使用数组在没有子查询的情况下执行此操作。基本上,取最后一个不计算 NULL
的元素:
select idx, value,
(array_remove(array_agg(value) over (order by idx), null))[count(value) over (order by idx)]
from base b
order by idx;
Here是一个数据库<> fiddle 。
关于sql - PostgreSQL last_value 忽略空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728095/