首页 > 解决方案 > 根据最小值重置累积总数并在 SQL 中用标志指示

问题描述

伸出手,因为我完全被困住了。

我有一组数据,其中每一行是一个收入金额,主键是一个序列号,所以例如看这里:SQLfiddle

我需要(1)创建一个等于“1”的标志,以指示累积总数何时达到最小值,例如 50。然后(2)将该累积总数重置为 0,并在下一次将其重新拾取序列。

我的尝试在下面,也在 SQLfiddle 中,但它不是一个好地方。

对于“new_cumulative_total”列,我预计第二行为 50,第三行为 58,第四行为 5,最后一行为 29。

对于“准备支付”列,我希望任何时候 new_cumulative_total 大于或等于 50 时为“1”,否则为“0”。

我知道这里可能需要做一些窗口函数魔法,但遗憾的是我还不够熟练,无法做到这一点。有人可以建议吗?非常感谢您!

with details as (

select
*,
sum(earning) over(order by sequence asc) as cumulative_total,
case when sum(earning) over(order by sequence asc) >= 50 then 1 else 0 end as ready_for_payout
from running_total_reset_example

)

select
*,
case when ready_for_payout = 1 then 0 else cumulative_total end as new_cumulative_total
from details

标签: sqlsql-server

解决方案


我已经在 SQL Server Management Studio 中编写了以下代码,并且能够获得所需的结果。

begin
    create  table #tbl1 (sequence int, earning int, cumulative_total_1 int, cumulative_total_2 int)
    insert into #tbl1 select sequence, earning, 0, 0 from running_total_reset_example

    declare c1 cursor for (select sequence, earning from running_total_reset_example)
    declare @sequence int = 0, @earning int=0, @cumulative_total_1 int=0, @cumulative_total_2 int=0, @sum1 int = 0, @sum2 int = 0
    open c1
    fetch next from c1 into @sequence , @earning  
    while (@@FETCH_STATUS = 0)
    begin   
        set @sum1 = @sum1 + @earning
        set @sum2 = @sum2 + @earning
        if @sum2 >= 50 
            begin
                    set @sum2 = 0
            end
        Update #tbl1
            set cumulative_total_1 = @sum1, cumulative_total_2 = @sum2
            where [sequence] = @sequence
        fetch next from c1 into @sequence , @earning
    end
    close c1
    deallocate c1
    select sequence, earning, cumulative_total_1, cumulative_total_2, 
    (case cumulative_total_2
        when 0 then 1
        else 0
     end) as ready_for_payout
    from #tbl1
    drop table #tbl1
end

推荐阅读