SQL,仅对第一个空值进行向后填充,仅对最后一个空值进行前向填充,对其他空值进行线性插值

问题描述 投票:0回答:1

如何在 bigquery 中对具有列时间戳的表中的列进行向后、向前和线性插值填充?

我有这张桌子:

时间戳 霉菌
1
2
3 69
4
5 71
6 72
7

我期望这样的结果:

时间戳 霉菌
1 69
2 69
3 69
4 70
5 71
6 72
7 72
sql google-bigquery imputation
1个回答
0
投票

请参阅下面的查询,

WITH input_data as (
  SELECT 1 as _timestamp,   null as my_col
  UNION ALL
  SELECT 2 as _timestamp,   null as my_col
  UNION ALL
  SELECT 3 as _timestamp,   69 as my_col
  UNION ALL
  SELECT 4 as _timestamp,   null as my_col
  UNION ALL
  SELECT 5 as _timestamp,   71 as my_col
  UNION ALL
  SELECT 6 as _timestamp,   72 as my_col
  UNION ALL
  SELECT 7 as _timestamp,   null as my_col
) SELECT *,IFNULL(IFNULL(my_col,FIRST_VALUE(my_col IGNORE NULLS)
                  OVER (item_window ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING )
                  ), -- inner ifnull/firstvalue block to select first not null value
           LAG(my_col) OVER (ORDER BY _timestamp, my_col)) AS new_value --outer ifnull/lag block to correct trailing nulls/blanks
FROM input_data
WINDOW item_window as (ORDER BY input_data._timestamp)

在屏幕截图中查看查询输出

© www.soinside.com 2019 - 2024. All rights reserved.