SQL 按百分比减少总和

jan*_*ane 5 sql snowflake-cloud-data-platform

我有一张像这样的桌子

时间戳 类型 价值
2023年1月8日 1 5
2023年1月7日 0 20
2023年1月6日 1 1
2023年1月5日 0 50
2023年1月4日 0 50
2023年1月3日 1 1
2023年1月2日 1 1
2023年1月1日 1 1

类型1表示存款,类型0表示取款。问题是,当类型为 1 时,金额就是用户存入的确切金额,因此我们可以将其相加,但类型 0 表示以百分比形式提款。我正在寻找的是创建另一个包含当前存入金额的列。对于上面的例子来说,它看起来像这样。

时间戳 类型 价值 存入
2023年1月8日 1 5 5.4
2023年1月7日 0 20 1.4
2023年1月6日 1 1 1.75
2023年1月5日 0 50 0.75
2023年1月4日 0 50 1.5
2023年1月3日 1 1 3
2023年1月2日 1 1 2
2023年1月1日 1 1 1

我不知道如何计算这样的总和,这会减去之前总数的百分比

Sim*_*rim 2

您试图随着时间的推移携带状态,因此以太坊需要使用 UDTF 来为您完成携带工作。或者使用递归 CTE

with data(transaction_date, type, value) as (
    select to_date(column1, 'dd.mm.yyyy'), column2, column3
    from values
        ('08.01.2023', 1, 5),
        ('07.01.2023', 0, 20),
        ('06.01.2023', 1, 1),
        ('05.01.2023', 0, 50),
        ('04.01.2023', 0, 50),
        ('03.01.2023', 1, 1),
        ('02.01.2023', 1, 1),
        ('01.01.2023', 1, 1)
), pre_process_data as (
    select *
        ,iff(type = 0, 0, value)::number as add
        ,iff(type = 0, value, 0)::number as per
        ,row_number()over(order by transaction_date asc) as rn
    from data 
), rec_cte_block as (
    with recursive rec_sub_cte as (
        select 
            p.*,
            p.add::number(20,4) as deposited
        from pre_process_data as p
        where p.rn = 1
        
        union all 
        
        select 
            p.*,
            round(div0((r.deposited + p.add)*(100-p.per), 100), 2)  as deposited
        from rec_sub_cte as r
        left join pre_process_data as p
        where p.rn = r.rn+1
    )
    select * 
    from rec_sub_cte
)
select * exclude(add, per, rn)
from rec_cte_block
order by 1;
Run Code Online (Sandbox Code Playgroud)

我以这种方式编写了递归 CTE,因为目前如果在 CTE 内部使用 IFF 或 CASE 会发生事件。

交易日期 类型 价值 已存入
2023-01-01 1 1 1
2023-01-02 1 1 2
2023-01-03 1 1 3
2023-01-04 0 50 1.5
2023-01-05 0 50 0.75
2023-01-06 1 1 1.75
2023-01-07 0 20 1.4
2023-01-08 1 5 6.4