簡體   English   中英

Big Query 在最近日期加入

[英]Big Query Join on Closest Date

您好我正在嘗試使用兩個字段在 bigquery 中加入兩個表,其中一個是日期字段,另一個是貨幣代碼。

示例數據:

sales_table
|sales_id|currency|   date   |value| 
|1234    |GBP     |2020-01-10| 1.50|
|1235    |GBP     |2020-01-15| 1.48|
|1236    |GBP     |2020-01-20| 1.49|
currency_table
|currency|   date   | rate|
|GBP     |2020-01-10| 0.89|
|GBP     |2020-01-15| 0.89|
|GBP     |2020-01-19| 0.89|

這個想法是獲取特定日期的 exchange_rate 我並不總是在 currency_table 上有所有日期,所以我想加入最接近的值。 我怎樣才能做到這一點? 我嘗試使用CROSS JOIN ,但數據的大小(銷售表上的 5M 行)使其幾乎無法使用。 有任何想法嗎?

您可以使用 window 函數執行此操作:

with cte as (
      select sales_id, currency, date, value, null as rate
      from sales 
      union all
      select null, currency, date, null, rate
      from currency_table
     )
select sales_id, currency, date, value, imputed_rate
from (select cte.*,
             last_value(rate ignore nulls) over (partition by currency order by date) as imputed_rate
      from t
     ) t
where sales_id is not null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM