提问人:naomitrina 提问时间:7/13/2023 最后编辑:naomitrina 更新时间:7/28/2023 访问量:157
使用 Snowflake 中的先前值回填数据
backfill data using previous values in Snowflake
问:
我在 Snowflake 中有一个表,其中包含在月底更新的数据以及每天更新的数据 (t2)。我已经加入了这些表,现在我需要滞后每月更新的数据点,直到每月 filingDate 等于 AsOfDate。
这是我的表格的样子:
AsOfDate(日期) | 每日值 | 编号 | 申报日期 | 月度值 |
---|---|---|---|---|
7/05/23 | 158 | 45 | 零 | 零 |
7/04/23 | 157 | 45 | 零 | 零 |
7/03/23 | 157 | 45 | 零 | 零 |
7/02/23 | 154 | 45 | 零 | 零 |
7/01/23 | 152 | 45 | 零 | 零 |
6/30/23 | 152 | 45 | 6/30/23 | 4 |
7/05/23 | 34 | 67 | 零 | 零 |
7/04/23 | 33 | 67 | 零 | 零 |
7/03/23 | 32 | 67 | 零 | 零 |
7/02/23 | 28 | 67 | 零 | 零 |
7/01/23 | 28 | 67 | 零 | 零 |
6/30/23 | 23 | 67 | 6/30/23 | 82 |
这是我需要我的表格的样子:
AsOfDate(日期) | 每日值 | 编号 | 申报日期 | 月度值 |
---|---|---|---|---|
7/05/23 | 158 | 45 | 6/30/23 | 4 |
7/04/23 | 157 | 45 | 6/30/23 | 4 |
7/03/23 | 157 | 45 | 6/30/23 | 4 |
7/02/23 | 154 | 45 | 6/30/23 | 4 |
7/01/23 | 152 | 45 | 6/30/23 | 4 |
6/30/23 | 152 | 45 | 6/30/23 | 4 |
7/05/23 | 34 | 67 | 6/30/23 | 82 |
7/04/23 | 33 | 67 | 6/30/23 | 82 |
7/03/23 | 32 | 67 | 6/30/23 | 82 |
7/02/23 | 28 | 67 | 6/30/23 | 82 |
7/01/23 | 28 | 67 | 6/30/23 | 82 |
6/30/23 | 23 | 67 | 6/30/23 | 82 |
6/29/23 | 22 | 67 | 6/27/23 | 80 |
6/28/23 | 21 | 67 | 6/27/23 | 80 |
6/27/23 | 20 | 67 | 6/27/23 | 80 |
6/26/23 | 19 | 67 | 5/31/23 | 77 |
我尝试使用row_number来查找每个 ID 的最新申请日期。
select row_number over (partition by id order by filingDate desc) as rn
所以 rn = 1 是每个日期的最新 filingDate,然后我尝试使用 update 语句。
update table
set MonthlyValue = (select b.MonthlyValue
from table b
where rn = 1 and b.id = a.id and b.MonthlyValue is not null)
from table a
where a.MonthlyValaue is null
这在 Snowflake 中不起作用。我收到不支持的子查询类型的错误消息。但是,老实说,我想不出没有子查询的方法。任何帮助将不胜感激!!
答:
0赞
Maja F.
7/14/2023
#1
这类问题经常出现,以至于我写了一篇关于它的博客文章:使用 Snowflake SQL 创建缺失的记录。
查看使用 LAST_VALUE() 函数的语法。
评论
0赞
naomitrina
7/27/2023
我使用 last_value() 在 Snowflake 中尝试了多种查询变体,但没有一个奏效。我仍然只看到 null where filingDate 为 null。SELECT AsOfDate, DailyValue, ID, LAST_VALUE(FilingDate IGNORE NULLS) OVER (PARTITION BY ID ORDER BY AsOfDate ) AS FilingDate, LAST_VALUE(MonthlyValue IGNORE NULLS) OVER (PARTITION BY ID ORDER BY FilingDate desc ) AS MonthlyValue FROM table
0赞
Maja F.
7/28/2023
您的查询在您提供的示例数据上完全正常。你还有其他不工作的例子吗?
0赞
naomitrina
7/28/2023
对我来说,查询只是为每个 AsOfDate 重新设置相同的 FilingDate。但是,我只想在 FilingDate 小于 AsOfDate 的地方进行回填。我尝试使用一种情况,当 FilingDate < AsOfDate 然后在查询中last_value(MonthlyValue IGNORE NULLS) over (Partition by ID, Order by FilingDate desc) else MonthlyValue 时,但这也没有产生我想要的。
0赞
naomitrina
7/28/2023
我在所需的输出表中添加了几行来说明这一点。我只需要 last_value(filingDate) 和 last_value(MonthlyValue),其中 FilingDate < AsOfDate。
0赞
Maja F.
7/29/2023
试试这个:SELECT AsOfDate, DailyValue, ID, LAST_VALUE(FilingDate IGNORE NULLS) OVER (PARTITION BY ID ORDER BY AsOfDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS FilingDate, LAST_VALUE(MonthlyValue IGNORE NULLS) OVER (PARTITION BY ID ORDER BY AsOfDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS MonthlyValue FROM table
上一个:基于货币对相关性计算回撤
评论