组中Redshift中的最后一个非空值 [英] Last Non-Null Value in Redshift by Group
本文介绍了组中Redshift中的最后一个非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Redshift,并希望通过用户ID接收最后一个非null值.
I am using Redshift and want to receive the last non-Null value by userid.
这是示例数据集:
Date UserID Value
4-18-2018 abc 1
4-19-2018 abc NULL
4-20-2018 abc NULL
4-21-2018 abc 8
4-19-2018 def 9
4-20-2018 def 10
4-21-2018 def NULL
4-22-2018 tey NULL
4-23-2018 tey 2
如果新用户以NULL开头,则替换为0.
If the new user starts out with a NULL then replace with 0.
我希望我的最终数据集看起来像这样:
I want my final dataset to look like this:
Date UserID Value
4-18-2018 abc 1
4-19-2018 abc 1
4-20-2018 abc 1
4-21-2018 abc 8
4-19-2018 def 9
4-20-2018 def 10
4-21-2018 def 10
4-22-2018 tey 1
4-23-2018 tey 2
任何帮助将非常感谢!
推荐答案
您可以使用lag()
和ignore nulls
选项执行此操作:
You can do this with lag()
and the ignore nulls
option:
select date, userid,
coalesce(value, lag(value ignore nulls) over (partition by userid order by date)) as value
from t;
如果值增加,则还可以使用累积最大值:
If the values are increasing, you can also use a cumulative maximum:
select date, userid,
max(value) over (partition by userid order by date) as value
from t;
这篇关于组中Redshift中的最后一个非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文