我正在尝试在这里执行某些操作。我想让所有颜色填充值。但是,当我有空列时,我想用前一个非空列中的值填充它。
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。我想我在这里缺少什么,但现在不知道了。
谢谢!
这应该与您的cte
定义一起使用:
...
select timestamp,
owner_id,
owner_assigneddate,
lastmodifieddate,
LAST_VALUE(owner_id IGNORE NULLS)
OVER(ORDER BY timestamp ASC ROWS BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW) AS test_column
from cte order by timestamp asc
就所关注的而言,Big Query在窗口函数中不支持ignore null
。这是一个依赖窗口最大值的解决方案,用于查找保存最后一个非空owner_id
的记录:
select
c.timestamp,
coalesce(c.owner_id, c_lag.owner_id) owner_id,
c.owner_assigneddate,
c.lastmodifieddate
from
(
select
cte.*,
max(case when owner_id is not null then timestamp end)
over(order by timestamp rows unbounded preceding) target_timestamp
from cte
) c
left join cte c_lag
on c.owner_id is null
and c_lag.timestamp = c.target_timestamp