【问题标题】:Calculate from previous rows in BigQuery根据 BigQuery 中的先前行计算
【发布时间】:2021-02-25 01:13:24
【问题描述】:

我需要从之前的原始数据中计算pending_principal,有什么我可以直接在SQL 中执行此操作的吗?我正在使用 BigQuery。

样本数据

Date Pending_principal
2020-01-01 1000000

我想计算未来 5 天的 pending_principal

我希望结果

Date Late_fee Pending_principal
2020-01-01 0 1000000
2020-01-02 50000 1050000
2020-01-03 52500 1102500
2020-01-04 55125 1157625
2020-01-05 50000 1050000

late_fee 的逻辑

late_fee=5% * 上一行pending_principal

pending_principal 的逻辑

pending_principal=上一个pending_principal+late_fee

这在某种程度上是可能的吗?

【问题讨论】:

  • 编辑您的问题并显示您想要的结果。
  • 请提供示例数据并期望输出(我假设这是当前的表格展示,如果为真添加一些文本以表明它是期望输出)。
  • 你的问题没有多大意义。 late_fee 如何依赖于 pending_principal,而 pending_principal 又如何依赖于 late_fee?你的能力不应该是0吗?您需要展示原始数据和您的预期结果。
  • 一般来说,递归公用表表达式可以在 Oracle、Sql Server、DB2 等中发挥作用。这个问题和答案应该为您指明关于 BigQuery 的正确方向:stackoverflow.com/questions/59890459/…

标签: sql google-bigquery


【解决方案1】:

我发布此答案是为了其他 SQL 用户的利益。我不确定 BigQuery 目前是否支持递归公用表表达式。我发布了一些命令式循环语法的链接,可能会在问题 cmets 中完成这项工作。

with recursive rcte as
(
    select 

        seed."date"
        , seed.fee
        , seed.pending

    from 

        (values  (cast('2020-01-01' as date), 0, 1000000)) as seed("date", fee, pending)

    union all
    
    select
    
        cast(rcte."date" + interval '1 day' as date) as "when"
        , cast(rcte.pending * 0.05 as int) as fee
        , cast(rcte.pending * 1.05 as int) as pending
    
    from
    
        rcte

    where
    
        rcte."date" < cast('2020-01-10' as date)
        
)

select

    *

from 

    rcte

;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2021-11-07
    • 2023-04-10
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多