sql - 根据最小值重置累积总数并在 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
解决方案
我已经在 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
推荐阅读
- java - 使用 Glide 将图像添加到工具栏
- sql - 将多个 self JOIN 转换为窗口函数或子查询 (SQL)
- python - 使用 Python 的 LazyLoader 导入类导入顶级模块
- javascript - 用 jQuery 替换外部 CSS 中的自定义属性
- django - 从 Django 模板中的嵌套列表生成表
- php - 此集合实例上不存在属性 [lesson_id] - 即使我使用的是 foreach,因此仅检索 1 个模型
- node.js - newman: 找不到“htmlextra”reporter 确保reporter 安装在与newman 相同的目录中 请使用npm 安装reporter
- java - 错误:在包“android”中找不到属性“requestLegacyExternalStorage”和“preserveLegacyExternalStorage”的资源标识符
- python - 我收到此错误有人可以帮助我吗
- git - 在修订版 go/database/v1.0.1 阅读 github.com/username/kit/go/database/go/database/go.mod:未知修订版 go/database/v1.0.1