用下一个非空值填补空白

Filling gaps with next not null value

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


|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

谢谢!

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

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