sql - PostgreSQL last_value 忽略空值

标签 sql postgresql null window-functions

我知道有人问过这个问题,但为什么下面的解决方案不起作用?我想用 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/

相关文章:

sql - 如何创建索引以避免与 DISTINCT 一起使用的排序步骤?

sql - 使用触发器记录更新行的时间是个好主意吗?

postgresql - 为具有多种元素种类的库存控制系统建模

hibernate - Grails/hibernate : how to order by isnull(property) to get NULLs last?

mysql - 如何选择零结果mysql?

jsf - @ManagedProperty 不反射(reflect)变化并一直返回 null

mysql - 使用mysql查询获取每月金额

php - 使用当前数据+另一个表中定义的范围中的随机数更新数据库表

sql - 优化 PostgreSQL 中的 SQL 查询

postgresql - 如何在postgresql8.2中将base64字符串转换为bytea