Agr*_*hak 5 sql postgresql null window-functions
我知道已经有人问过这个问题,但为什么下面的解决方案不起作用?我想填充value按 排序的最后一个非空值idx。
我所看到的:
idx | coalesce
-----+----------
1 | 2
2 | 4
3 |
4 |
5 | 10
(5 rows)
Run Code Online (Sandbox Code Playgroud)
我想要的是:
idx | coalesce
-----+----------
1 | 2
2 | 4
3 | 4
4 | 4
5 | 10
(5 rows)
Run Code Online (Sandbox Code Playgroud)
代码:
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
Run Code Online (Sandbox Code Playgroud)
你想要的是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;
Run Code Online (Sandbox Code Playgroud)
您也可以使用数组来执行此操作,而无需子查询。基本上,取最后一个不包括NULLs 的元素:
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;
Run Code Online (Sandbox Code Playgroud)
这是一个 db<>fiddle。
那么这里的last_value对我来说没有意义,除非你能向我指出。查看示例,您需要最后一个非值,您可以通过以下方式获取它:我正在使用空值和先前的非空值形成一个组,以便我可以获得第一个非值。
with base as (
select 1 as idx , 2 as value union
select 2 as idx, -14 as value union
select 3 as idx , null as value union
select 4 as idx , null as value union
select 5 as idx , 1 as value
)
Select idx,value,
first_value(value) Over(partition by rn) as new_val
from(
select idx,value
,sum(case when value is not null then 1 end) over (order by idx) as rn
from base
) t
Run Code Online (Sandbox Code Playgroud)
这是代码
http://sqlfiddle.com/#!15/fcda4/2
要了解您的解决方案不起作用的原因,只需查看输出(如果您按照窗口框架中的顺序进行排序):
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, value from base
order by case when value is null then -1
else idx
end;
idx | value
-----+-------
3 |
4 |
1 | 2
2 | 4
5 | 10
Run Code Online (Sandbox Code Playgroud)
last_value() 窗口函数将选取当前帧中的最后一个值。在不更改任何框架默认值的情况下,这将是当前行。