未定义行数的计算

calculation with undefined number of rows

考虑到我们可以有一个、两个、三个或更多行,我想添加一个计算。我们可以使用关系获取所有数据,但我有点卡住了,因为关系的数量未定义。 例如,作为来源:

SELECT 123 AS id
      ,250 AS amount
      ,225 AS debt
      ,NULL AS relation
      ,1 AS rn
UNION ALL    
SELECT 124 AS id
      ,150 AS amount
      ,25 AS debt
      ,123 AS relation
      ,2 AS rn
UNION ALL   
SELECT 125 AS id
      ,160 AS amount
      ,50.25 AS debt
      ,124 AS relation
      ,3 AS rn
UNION ALL
SELECT 126 AS id
      ,80 AS amount
      ,25 AS debt
      ,125 AS relation
      ,4 AS rn 

来源Table

id amount debt relation rn
123 250 225 NULL 1
124 150 25 123 2
125 160 50.25 124 3
126 80 25 125 4

结束Table

id amount debt relation rn cal
123 250 225 NULL 1 250
124 150 25 123 2 22.5
125 160 50.25 124 3 7.5375
126 80 25 125 4 3.75

我需要应用这样的计算:

我正在使用 dbt,但很高兴听到有关 BigQuery 或其他 SQL 的消息,因为我真的很好奇如何做到这一点。

一点点数学知识可以帮到你 - 见下文

select *,
  ifnull(
    round(exp(sum(ln(debt)) over(order by id rows between unbounded preceding and current row))
    / exp(sum(ln(amount)) over(order by id rows between unbounded preceding and 1 preceding)), 2),
    amount
  ) cal
from `project.dataset.table`  

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

注意:我使用 order by id 假设 id 列定义了行的顺序。您可以根据需要进行调整