【问题标题】:SQL Server cumulative sum with restricted range范围受限的 SQL Server 累积总和
【发布时间】:2021-06-21 19:42:47
【问题描述】:

给定一张人员表和与他们的评估相关的分数,我需要获取他们每次评估的累积分数(按人)。

Person EvaluationDate Score
Jane 2012 -12
Hubert 2014 -5
Jane 2020 -5
Jane 2015 +16
Hubert 2011 -100

他们的分数从100开始,不能低于0或超过100。如果在某个时间分数超过100(或低于0),则从100(或0)开始计算下一个累积分数。

预期输出:

Person EvaluationDate Score CumulativeScore
Hubert 2011 -100 0
Hubert 2014 -5 0
Jane 2012 -12 88
Jane 2015 +16 100
Jane 2020 -5 95

posts describing how to do a cumulative sum,但他们没有解释如何通过每个操作将其限制在一个范围内。

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

正如@LukaszSzozda 在他的评论中建议的那样,您可以使用递归 CTE。

with t as (
   select Person, EvaluationDate, Casescore,
       row_number() over(partition by Person order by EvaluationDate) rn
   from tbl 
), rq as(
   select *,
       case when 100 + Casescore < 0   then 0
            when 100 + Casescore > 100 then 100
            else 100 + Casescore end CumulativeScore
   from t
   where rn = 1
   
   union all 
   
   select t.Person, t.EvaluationDate, t.Casescore, t.rn,
       case when rq.CumulativeScore + t.Casescore < 0   then 0
            when rq.CumulativeScore + t.Casescore > 100 then 100
            else rq.CumulativeScore + t.Casescore end 
   from rq
   join t on t.rn = rq.rn + 1 and t.Person = rq.Person
)
select Person, EvaluationDate, Casescore, CumulativeScore
from rq
order by Person, EvaluationDate;

db<>fiddle

【讨论】:

  • 谢谢!在处理许多评估时会引发递归错误,在查询末尾附加 option (maxrecursion 0) 可以解决问题
猜你喜欢
  • 2018-03-05
  • 2022-06-10
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多