[英]Replace first and last row having null values or missing values with previous/next available value in Postgresql12
I am a newbiew to postgresql.我是 postgresql 的新手。 I want to replace my first and last row of table,T which has null or missing values, with next/previous available values.我想用下一个/上一个可用值替换具有 null 或缺失值的表 T 的第一行和最后一行。 Also, if there are missing values in the middle, it should be replaced with previous available value.此外,如果中间有缺失值,则应将其替换为以前的可用值。 For example:例如:
id value EXPECTED
1 1
2 1 1
3 2 2
4 2
5 3 3
6 3
I am aware that there are many similar threads, but none seems to address this problem where the start and end also have missing values (including some missing in the middle rows).我知道有许多类似的线程,但似乎没有一个解决这个问题,其中开始和结束也有缺失值(包括中间行中的一些缺失)。 Also some of the concepts such as first_row,partition by, top 1(which does not work for postgres) are very hard to grasp as a newbie.此外,一些概念,如 first_row、partition by、top 1(不适用于 postgres)作为新手很难掌握。
So far i have referred to the following threads: value from previous row and Previous available value到目前为止,我已经提到了以下线程: 上一行的值和上一个可用值
Could someone kindly direct me in the right direction to address this problem?有人可以指导我正确的方向来解决这个问题吗? Thank you谢谢
Unfortunately, Postgres doesn't have the ignore null
s option on lead()
and lag()
.不幸的是,Postgres 在lead()
和lag()
上没有ignore null
s 选项。 In your example, you only need to borrow from the next row.在您的示例中,您只需要从下一行借。 So:所以:
select t.*,
coalesce(value, lag(value) over (order by id), lead(value) over (order by id)) as expected
from t;
If you had multiple NULLs in a row, then this is trickier.如果您连续有多个 NULL,那么这会比较棘手。 One solution is to define "groups" based on when a value starts or stops.一种解决方案是根据值开始或停止的时间来定义“组”。 You can do this with a cumulative count of the values -- ascending and descending:您可以使用值的累积计数来执行此操作 - 升序和降序:
select t.*,
coalesce(value,
max(value) over (partition by grp_before),
max(value) over (partition by grp_after)
) as expected
from (select t.*,
count(value) over (order by id asc) as grp_before,
count(value) over (order by id desc) as grp_after
from t
) t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.