在没有子查询的情况下获取 BigQuery 中给定日期的最接近日期

Getting the closest date to a given date in BigQuery with no subqueries

试图回到购买发生时的货币兑换率,因此收入计算是准确的。 BigQuery 不支持子查询,所以像这两个查询这样的操作是行不通的(它们在数据库上工作):

查询 1

SELECT
  b.id,
  j.id,
  j.currency,
  j.created,
  j.status,
  j.pricev,
  j.price,
  (
    select 
      erc.rfbcurr 
    from 
      test.exchangerates_exchangeratechange erc 
    join 
      test.exchangerates_exchangerate er on er.id = erc.exchangerateid
    where 
      erc.created < j.created and er.currencycode = j.currency 
    order by 
      erc.created desc
    limit 1
  ) as exchangerate
FROM 
  transferz-st.test.bs_b b
JOIN 
  transferz-st.test.bs_j j on j.bid = b.id;

查询 2

 SELECT
  b.id,
  j.id,
  j.currency,
  j.created,
  j.status,
  j.pricev,
  j.price,
  j.currency,
  erc.rfbcurr
FROM
  b
JOIN
  j on j.bid = b.id
JOIN
  exchangerate er on er.currencycode = j.currency
JOIN
  exchangeratechange erc on erc.exchangerateid = er.id
GROUP BY
  b.id,
  j.id,
  j.currency,
  j.created,
  j.status,
  j.pricevat,
  j.price,
  j.currency,
  erc.rfbcurr,
  erc.id
HAVING
    erc.id = (select erc2.id from exchangeratechange erc2 join exchangerate er2 on er2.id = rc2.id where erc2.created < j.created and er2.currencycode = j.currency order by erc2.created desc limit 1);

有人可以提出解决方案吗?

您可以尝试使用 JOIN 引入货币汇率。使用 LEAD() 获取日期范围:

WITH er AS (
      select erc.rfbcurr, er.currencycode, er.created, 
             lead(er.created) over (partition by er.currencycode order by er.created) as next_created
      from  test.exchangerates_exchangeratechange erc join 
            test.exchangerates_exchangerate er
            on er.id = erc.exchangerateid
     )
SELECT . . ., er.rfbcurr as exchange_rage
FROM transferz-st.test.bs_b b JOIN 
     transferz-st.test.bs_j j 
     ON j.bid = b.id JOIN
     er
     ON er.currencycode = j.currency AND
        j.created >= er.created AND
        (er.next_created IS NULL OR j.created < er.next_created);