【问题标题】:Last Non-Null Value in Redshift by GroupRedshift 中的最后一个非空值(按组)
【发布时间】:2023-03-03 17:06:01
【问题描述】:

我正在使用 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

任何帮助将非常感谢!

【问题讨论】:

    标签: sql null amazon-redshift lag


    【解决方案1】:

    您可以使用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;
    

    【讨论】:

    • 我创建了一个新列来查看差异,看起来它正在通过执行上述方法更改值列。是否可以简单地按组(用户 ID)取空值以上的值,如果空值之前没有用户 ID,则将其设为“1”?
    • @NickKnauer 。 . .应该有一个coalesce() 来保留现有值。
    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多