需求贴:
http://topic.csdn.net/u/20110423/13/f5b302f4-417d-4890-995e-65a5b5fb23ce.html?seed=1731769063&r=72947420#r_72947420
--要求说明
例如下表中有充值记录,每个人可能充值多次,当消费的时候,根据消费金额更新充值记录
例如张三充值3次,分别为17,2,12,假设其消费22元,则更新为0,0,9 就是说17和2的两笔钱花完了,12那笔钱还剩9元。如果消费18元,则更新为0,1,12。如果消费了13元,则变成4,2,12。
--测试数据
declare @info table (编号int,姓名varchar(4),金额int)
insert into @info
select 1,'张三',17 union all
select 2,'李四',210 union all
select 3,'张三',2 union all
select 4,'李四',12 union all
select 5,'张三',12
--张三消费22
declare @i int;set @i=22
update @info
set @i=case when @i<0 then 0 else @i-金额end,
金额=case when @i>0 then 0 when @i=0 then 金额else -@i end
where 姓名='张三'
select * from @info
/*
编号 姓名 金额
----------- ---- -----------
1 张三 0
2 李四 210
3 张三 0
4 李四 12
5 张三 9
*/
首先感谢Freedom0227,发现我上面的代码并不适用于所有的情况。
现换了思路重新写了一个:
declare @infomation table (编号 int,姓名 varchar(4),金额 int) insert into @infomation select 1,'张三',17 union all select 2,'李四',210 union all select 3,'张三',2 union all select 4,'李四',12 union all select 5,'张三',12 --张三消费22 declare @i int;set @i=19 declare @j int;declare @k int ;with maco as ( select * from @infomation where 姓名='张三'),maco1 as( select *,总金额=(select sum(金额) from maco where 编号<=a.编号) from maco a) select top 1 @j=编号,@k=总金额-@i from maco1 where 总金额>=@i update @infomation set 金额=@k where 编号=@j update @infomation set 金额=0 where 姓名='张三' and 编号<@j select * from @infomation /* 编号 姓名 金额 ----------- ---- ----------- 1 张三 0 2 李四 210 3 张三 0 4 李四 12 5 张三 12 */