Update @tb Set Outcome = 60 + Score Where sesion = 1
Declare @Session decimal(18,0)
Declare F Cursor For Select sesion From @tb Where sesion <> 1 Order By sesion
Open F
Fetch Next From F Into @MaID
While @@FETCH_STATUS = 0
Begin
Update @tb
Set Outcome = Case When Score + (Select Outcome From @tb Where sesion = @Session - 1) > 100 Then 100
When Score + (Select Outcome From @tb Where sesion = @Session - 1) < 0 Then 0
Else Score + (Select Outcome From @tb Where sesion = @Session - 1) End
Where sesion = @Session
Fetch Next From F Into @Session
End
Close F
DeAllocate F
with recursive cte (id, session_no, score, outcome) as (
select id, session_no, score, 60+score as outcome
from session_score
where session_no = 1
union all
select ss.id, ss.session_no, ss.score,
case
when c.outcome + ss.score > 100 then 100
when c.outcome + ss.score < 0 then 0
else c.outcome + ss.score
end as outcome
from session_score ss
join cte c
on ss.id = c.id
and ss.session_no = c.session_no+1)
select id, session_no, score, outcome
from cte
order by 1,2;
SELECT
y.id,
y.nosession,
y.score,
@running_total :=
CASE WHEN @running_total + y.score > 100 THEN 100
WHEN @running_total + y.score < 0 THEN 0
ELSE @running_total + y.score END
AS cumulative_sum
FROM yourtable y
JOIN (SELECT @running_total := 60) r
ORDER BY y.id, y.nosession
这将适用于不同的ID:
SELECT sub.id, sub.nosession, sub.score, sub.cumulative_sum
FROM
(SELECT
y.id,
y.nosession,
y.score,
@running_total :=
CASE WHEN id <> @id THEN 60 + y.score
WHEN @running_total + y.score > 100 THEN 100
WHEN @running_total + y.score < 0 THEN 0
ELSE @running_total + y.score END
AS cumulative_sum,
@id := y.id
FROM yourtable y
JOIN (SELECT @running_total := 60, @id:='0') r
ORDER BY y.id, y.nosession) sub;
3条答案
按热度按时间toiithl61#
试试这个
eoxn13cs2#
下面是一个使用递归CTE的解决方案:
使用2个ID进行测试:
9rygscc13#
对于相同的id,这将正常工作:
这将适用于不同的ID:
请在此处试用:db<>fiddle