表A中有一字段 Amount
数据举例如下:
ID , Amount
1 2
2 1
3 4
现要实现的功能如下
按照上面的顺序 , 要减去一个 Amount 总数(比如 5)
则 更新后的数据如下
ID , Amount
1 0 //减掉了 5 中的 2
2 0 //减掉了 5 中的 1
3 2 //减掉了 5 中的 2
数据举例如下:
ID , Amount
1 2
2 1
3 4
现要实现的功能如下
按照上面的顺序 , 要减去一个 Amount 总数(比如 5)
则 更新后的数据如下
ID , Amount
1 0 //减掉了 5 中的 2
2 0 //减掉了 5 中的 1
3 2 //减掉了 5 中的 2
1、将满足条件之前的所以值都设为0;
update a set amount=0 where
a.id<(select max(a1.id) from a a1,(select sum(amount) sa from a a2 where a2.id<=a1.id) where sa<=5);
2.将最后一条的值设为剩下的差值。
insert into test values(1,2);
insert into test values(2,1);
insert into test values(3,4);
insert into test values(4,5);
select id,case when amount1<amount then amount1 else amount end as amount from(
select id,amount ,case when t<5 then 0 else t-5 end as amount1 from(
select id,amount,amount+ nvl((select sum(amount) from test where id<a.id),0) as t from test a
));
drop table test;
/*
ID AMOUNT
1 0
2 0
3 2
4 5
*/
select id,case when amount1<amount then amount1 else amount end as amount from(
select id,amount ,case when t<5 then 0 else t-5 end as amount1 from(
select id,amount,amount+ nvl((select sum(amount) from test where
id<a.id),0) as t from test a
))) q where q.id=p.id)
update 表 p
set
Amount=(case when (select sum(Amount) from 表 where ID<=p.ID)<=5 then 0
when (select sum(Amount) from 表 where ID< p.ID)<=5 then (select sum(Amount) from 表 where ID<p.ID)-5
else p.Amount
end)