【问题标题】:Filling gaps with next not null value用下一个非空值填充空白
【发布时间】:2021-10-15 11:03:49
【问题描述】:

从几天前开始,我一直在努力寻找解决方案。我有以下数据集。


|id|order|certain_event|order_of_occurrence|
|--|-----|-------------|-------------------|
|a |1    |NULL         |NULL               |
|a |2    |NULL         |NULL               |
|a |3    |NULL         |NULL               |
|a |4    |NULL         |NULL               |
|a |5    |4            |1                  |
|a |6    |NULL         |NULL               |
|a |7    |NULL         |NULL               |
|a |8    |4            |2                  |
|a |9    |NULL         |NULL               |

所需的输出包括用下一个非空值替换 order_of_occurrence 列中的空值。像这样:

|id|order|certain_event|order_of_occurrence|
|--|-----|-------------|-------------------|
|a |1    |NULL         |1                  |
|a |2    |NULL         |1                  |
|a |3    |NULL         |1                  |
|a |4    |NULL         |1                  |
|a |5    |4            |1                  |
|a |6    |NULL         |2                  |
|a |7    |NULL         |2                  |
|a |8    |4            |2                  |
|a |9    |NULL         |NULL               |

我尝试使用子查询从出现顺序列中检索非空值,但我得到了多个返回值。像下面这样:

SELECT a.*,
      CASE
         WHEN a.order_of_occurrence IS NOT NULL THEN a.order_of_occurence
         WHEN a.order_of_occurence IS NULL THEN (SELECT B.ORDER_OF_OCCURENCE FROM dataset AS B 
                                                 WHERE B.ORDER_OF_OCCURRENCE IS NOT NULL)
      END AS corrected_order
FROM dataset AS a

谢谢!

【问题讨论】:

    标签: sql teradata gaps-and-islands ansi-sql gaps-in-data


    【解决方案1】:

    这是 FIRST/LAST_VALUE 中 IGNORE NULLS 选项的简单任务:

    last_value(order_of_occurrence IGNORE NULLS)
    over (partition by id
          order by "order" DESC
          rows unbounded preceding)
    

    【讨论】:

    • 这正是我需要的选项!非常感谢!!
    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2015-07-22
    • 2017-07-19
    • 1970-01-01
    • 2019-11-21
    • 2015-09-17
    相关资源
    最近更新 更多