如何使用 BigQuery SQL 中的转换值从 table 创建转换率和货币类型列表?

How can I create a list of conversion rates and currency types from a table with converted values in BigQuery SQL?

我有一个很大的 table,有很多行。数据示例如下:

Currency Value Value_in_NOK
USD 100 800
USD 200 1600
SEK 120 108
USD 400 3200
SEK 240 216
USD 300 2400
EUR 15 150
EUR 30 300

转换后的值始终为挪威克朗。

我想要的是使用 SELECT statemnet 创建一个不同的货币列表,包括 NOK,第一行的货币汇率具有不同的货币:

Currency Currency_Rate
USD 8.000
SEK 0.900
EUR 10.000
NOK 1.000

假设您的 table 中有一些列定义了行的顺序 - 例如时间戳 (ts)

select Currency, array_agg(round(Value_in_NOK/Value, 3) order by ts limit 1)[offset(0)] as Currency_Rate
from your_table
group by Currency 
union all 
select 'NOK', 1.000    

如果应用于您问题中的示例数据 - 输出为

这是我最终得到的完美运行的代码。

SELECT
      Opportunity_First_year_value_Currency,
      ARRAY_AGG(ROUND(SAFE_CAST(Opportunity_First_year_value_converted AS NUMERIC)/SAFE_CAST(Opportunity_First_year_value AS NUMERIC), 5)
      ORDER BY 
        Opportunity_Close_Date DESC 
      LIMIT
        1) [
    OFFSET
      (0)] AS Currency_Rate
    FROM
      `JOINED_Opportunity`
    WHERE 
      SAFE_CAST(Opportunity_First_year_value_converted AS NUMERIC) > 0
    GROUP BY
      Opportunity_First_year_value_Currency
    UNION ALL
    SELECT
      'NOK',
      1.00000