declare @aa table ( id int, jine int)
insert into @aa values(1, 10)
insert into @aa values(2, 30)
insert into @aa values(3, 40)
insert into @aa values(4, 70)
insert into @aa values(5, 90)
insert into @aa values(6, 10)
select t2.id, case when t2.id < (select max(t1.id)
from @aa t1
where (select sum(t3.jine)
from @aa t3
where t3.id < t1.id) < 50)
then t2.jine
when t2.id = (select max(t1.id)
from @aa t1
where (select sum(t3.jine)
from @aa t3
where t3.id < t1.id) < 50)
then 50 - (select sum(t3.jine)
from @aa t3
where t3.id < t2.id)
else 0
end
from @aa t2
declare @aa table ( id int, jine int) --//建一个测试表
declare @i as int --//声明一个变量,用来累计jine,判断是否>50
declare @id as int --//返回一个ID
declare @diff as int --//返回距50还差多少
insert into @aa values(1, 10)
insert into @aa values(2, 30)
insert into @aa values(3, 40)
insert into @aa values(4, 70)
insert into @aa values(5, 90)
set @i=0 --//初始化
set @id=0 --//初始化
while (@i<50)
begin
set @id=@id+1 --//ID号自增
select @i=@i+jine from @aa where id =@id--//让语句单条执行
end
--print @id
select @diff=50-sum(jine) from @aa where id <@id--//找出跨50的那条记录之前的累计值和50的差值
--print @diff
update @aa set jine=@diff where id=@id --//更新跨50的那条记录
update @aa set jine=0 where id>@id --//更新跨50以后的记录
select * from @aa --//返回结果
declare @aa table ( id int, jine int)
insert into @aa values(1, 10)
insert into @aa values(2, 30)
insert into @aa values(3, 40)
insert into @aa values(4, 70)
insert into @aa values(5, 90)
select t2.id, case when t2.id < (select max(t1.id)
from @aa t1
where (select sum(t3.jine)
from @aa t3
where t3.id < t1.id) < 50)
then t2.jine
else 0
end
from @aa t2
select id,
case when (select sum(jin) from lingling b where b.id<=a.id) >50 then 0
else (select sum(jin) from lingling b where b.id<=a.id)
end as 'jine'
from lingling a
--楼主把下面的表名aa改为你的实际的表名就可以了
--建立函数
CREATE FUNCTION IFFifty(@ID INT)
RETURNS INT
AS
BEGIN
DECLARE @zonge INT,@Result INT
SET @zonge =0
SELECT @zonge=SUM(jine) FROM aa WHERE ID <=@ID
IF @zonge<50
SELECT @Result = jine FROM aa WHERE ID =@ID
ELSE
SELECT @Result=50-SUM(jine) FROM aa WHERE ID <@ID
INSERT INTO aa VALUES(10)
INSERT INTO aa VALUES(30)
INSERT INTO aa VALUES(40)
INSERT INTO aa VALUES(70)
INSERT INTO aa VALUES(90)
--建立函数
CREATE FUNCTION IFFifty(@ID INT)
RETURNS INT
AS
BEGIN
DECLARE @zonge INT,@Result INT
SET @zonge =0
SELECT @zonge=SUM(jine) FROM aa WHERE ID <=@ID
IF @zonge<50
SELECT @Result = jine FROM aa WHERE ID =@ID
ELSE
SELECT @Result=50-SUM(jine) FROM aa WHERE ID <@ID