【问题标题】:SQL decreasing sum by a percentageSQL 按百分比递减总和
【发布时间】:2023-02-06 13:30:48
【问题描述】:

我有一张桌子

timestamp type value
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

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

timestamp type value deposited
08.01.2023 1 5 5.4
07.01.2023 0 20 1.4
06.01.2023 1 1 1.75
05.01.2023 0 50 0.75
04.01.2023 0 50 1.5
03.01.2023 1 1 3
02.01.2023 1 1 2
01.01.2023 1 1 1

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

【问题讨论】:

  • 您的表是否也有时间戳或序列列?
  • 是的,它确实有时间戳
  • 将该列添加到您的样本数据和预期结果中。
  • 您无法获得那些日子的实际提款金额吗?
  • @Rajat 你不需要实际的提款金额来仅使用 SQL 来解决这个问题。

标签: sql snowflake-cloud-data-platform


【解决方案1】:

您正试图随时间携带状态,因此以太币需要使用 UDTF 来为您完成携带工作。或者使用recursive 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;

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

TRANSACTION_DATE TYPE VALUE DEPOSITED
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多