Sql 用于持久化值的BigQuery函数
在BigQuery中保存值的最佳方法是什么?例如,如果单元格中的值为Sql 用于持久化值的BigQuery函数,sql,google-bigquery,Sql,Google Bigquery,在BigQuery中保存值的最佳方法是什么?例如,如果单元格中的值为(none),则应获取最后一个已知值,该值不是(none),但如果该值随后发生更改,则开始保留该值。下面是我想要的例子。我尝试使用滞后函数,但它只适用于一行 Row Value Persisted 1 Apple Apple 2 (none) Apple 3 (none) Apple 4 (none) Apple 5
(none)
,则应获取最后一个已知值,该值不是(none)
,但如果该值随后发生更改,则开始保留该值。下面是我想要的例子。我尝试使用滞后函数,但它只适用于一行
Row Value Persisted
1 Apple Apple
2 (none) Apple
3 (none) Apple
4 (none) Apple
5 Orange Orange
6 (none) Orange
下面是BigQuery标准SQL 为了实现您的目标,您需要在数据中添加一些字段来定义值的顺序-通常是带有时间戳、日期等的列。数据类型或数字反映位置。在下面的示例中,我使用
ts
作为这样的列
#standardSQL
SELECT ts, value,
LAST_VALUE(IF(value = '(none)', NULL, value) IGNORE NULLS) OVER(ORDER BY ts) Persisted
FROM `project.dataset.table`
您可以使用问题中的样本数据测试、播放上述内容,如下例所示
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1 ts, 'Apple' Value UNION ALL
SELECT 2, '(none)' UNION ALL
SELECT 3, '(none)' UNION ALL
SELECT 4, '(none)' UNION ALL
SELECT 5, 'Orange' UNION ALL
SELECT 6, '(none)'
)
SELECT ts, value,
LAST_VALUE(IF(value = '(none)', NULL, value) IGNORE NULLS) OVER(ORDER BY ts) Persisted
FROM `project.dataset.table`
有输出
Row ts value Persisted
1 1 Apple Apple
2 2 (none) Apple
3 3 (none) Apple
4 4 (none) Apple
5 5 Orange Orange
6 6 (none) Orange