Redshift 中的最后一个非空值(按组)

Last Non-Null Value in Redshift by Group

我正在使用 Redshift 并希望通过用户 ID 接收最后一个非 Null 值。

这是一个示例数据集:

     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。

我希望我的最终数据集如下所示:

     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 选项:

select date, userid,
       coalesce(value, lag(value ignore nulls) over (partition by userid order by date)) as value
from t;

如果值在增加,您还可以使用累积最大值:

select date, userid,
       max(value) over (partition by userid order by date) as value
from t;