gpt4 book ai didi

sql - 如何使用前一行的值填充空列?

转载 作者:行者123 更新时间:2023-12-04 00:23:26 29 4
gpt4 key购买 nike

我想在这里表演一些东西。我想让所有的 coluns 都充满了值。但是当我有空列时,我想让它填充上一个非空列的值。

with cte as (
select '2019-11-12 16:01:55' as timestamp, null as owner_id, null as owner_assigneddate, null as lastmodifieddate union all
select '2019-11-12 19:03:18' as timestamp, 39530934 as owner_id, '2019-11-12 19:03:18' as owner_assigneddate, '2019-11-12 19:03:18' as lastmodifieddate union all
select '2019-11-12 19:03:19' as timestamp, null as owner_id, null as owner_assigneddate, '2019-11-12 19:03:19' as lastmodifieddate union all
select '2019-11-12 19:03:20' as timestamp, null as owner_id, null as owner_assigneddate, '2019-11-12 19:03:20' as lastmodifieddate union all
select '2019-11-12 19:03:31' as timestamp, 40320368 as owner_id, '2019-11-12 19:03:31' as owner_assigneddate, '2019-11-12 19:03:31' as lastmodifieddate union all
select '2019-11-12 19:03:33' as timestamp, null as owner_id, null as owner_assigneddate, '2019-11-12 19:03:33' as lastmodifieddate union all
select '2019-11-12 19:03:56' as timestamp, null as owner_id, null as owner_assigneddate, '2019-11-12 19:03:356' as lastmodifieddate)

select timestamp,
owner_id,
owner_assigneddate,
lastmodifieddate,
COALESCE(owner_id, LEAD(owner_id) OVER(ORDER BY timestamp DESC)) AS test_column
from cte order by timestamp asc

在上一个查询中,我已经设法将值仅放在下一行中。

我想要做的是让所有列都填充基于前一行的值。
第 4 行的值应为 39530934,第 7 行的值应为 40320368。
我想我在这里遗漏了一些东西,但我不知道是什么。

最佳答案

在 BigQuery 中使用 LAST_VALUE()IGNORE NULLS选项和 COALESCE() :

select timestamp,
COALESCE(owner_id, last_value(owner_id ignore nulls) over (order by timestamp)) as owner_id,
COALESCE(owner_assigneddate, LAST_VALUE(owner_assigneddate IGNORE NULLS) OVER (ORDER BY TIMESTAMP)) as owner_assigneddate,
COALESCE(lastmodifieddate, LAST_VALUE(lastmodifieddate IGNORE NULLS) OVER (ORDER BY TIMESTAMP)) as lastmodifieddate
from cte order by timestamp asc

关于sql - 如何使用前一行的值填充空列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58896032/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com