トランザクションが作成された時点で使用されていた通貨レートを取得するための簡単なクエリがあります。
SELECT t.orderid, t.date,
(SELECT rate FROM sources.currency_rates r WHERE currencyid=1 AND
r.date>=t.date ORDER BY date LIMIT 1) rate
FROM sources.transactions t
これによりエラーが発生します:
Error: Correlated subqueries that reference other tables are not
supported unless they can be de-correlated, such as by transforming
them into an efficient JOIN.'
いくつかの種類の結合と名前付きサブクエリを試しましたが、どれも機能しないようです。これを実現する最善の方法は何ですか? これは非常に一般的なシナリオのようで、BQ の標準 SQL で実装するのは非常に簡単なはずです。
ベストアンサー1
以下はBigQuery標準SQLの場合です
#standardSQL
SELECT
t.orderid AS orderid,
t.date AS date,
ARRAY_AGG(r.rate ORDER BY r.date LIMIT 1)[SAFE_OFFSET(0)] AS rate
FROM `sources.transactions` AS t
JOIN `sources.currency_rates` AS r
ON currencyid = 1
AND r.date >= t.date
GROUP BY orderid, date