我有下表(假设“名称”列按升序排列):
Name Tag
'a' 200
'b' 400
'c' null
'd' null
'e' null
'f' 100
'g' null
'h' null
'i' null
'j' 500
我想在 Snowflake 中编写一个 SELECT
查询以返回具有最小最近值的空值,如下所示:
Name Tag
'a' 200
'b' 400
'c' 400
'd' 400
'e' 400
'f' 100
'g' 100
'h' 100
'i' 100
'j' 500
如果我编写以下查询,它只会填充每个后续空组的第一个空值。
Select Name, coalesce(Tag, lag(Tag) over (order by Name)) as Tag
它返回:
Name Tag
'a' 200
'b' 400
'c' 400
'd' null
'e' null
'f' 100
'g' 100
'h' null
'i' null
'j' 500
有什么想法吗?
最佳答案
Snowflake 支持IGNORE NULLS
子句:https://docs.snowflake.com/en/sql-reference/functions/lag.html
因此,您的查询将是:
Select Name, tag as tag_original, coalesce(Tag, lag(Tag) IGNORE NULLS over (order by Name)) as Tag from tags;
Oracle 还支持IGNORE NULLS
:https://dbfiddle.uk/?rdbms=oracle_21&fiddle=d108ff84755240ec3b488aed08d80dc5
关于SQL select查询根据最接近的非空值填充空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73371665/