日期:2014-05-18 浏览次数:20504 次
update a set col2=case when (select sum(col2) from tb where col1=a.col1 and 时间<=a.时间)<=60 then 0 else col2-(select sum(col2) from tb where col1=a.col1 and 时间<=a.时间) end from tb a where col1 in ('a','b')
------解决方案--------------------
if object_id('tb','U') is not null drop table tb go create table tb ( c1 varchar(10), c2 int ) go insert into tb select 'A',50 union all select 'B',30 union all select 'A',10 union all select 'B',15 union all select 'C',35 union all select 'B',40 go with cte as ( select c1,c2,row=row_number() over(order by getdate()) from tb ) update a set c2=b.c2 from (select *,row=row_number() over(order by getdate()) from tb) a inner join ( select c1,row, c2=case when (select sum(c2) from cte where c1=t1.c1 and row<=t1.row)-60<0 then 0 else (select sum(c2) from cte where c1=t1.c1 and row<=t1.row)-60 end from cte t1 where c1='B' or C1='A' ) b on a.row=b.row /* c1 c2 ---------- ----------- A 0 B 0 A 0 B 0 C 35 B 25 (6 行受影响) */
------解决方案--------------------
把表结构和数据列出来,还有你想要的结果也列出来
------解决方案--------------------
在之后往里插入数据的时候要做一个插入的判断:
--对已有的 id xtype 类型要做累加或减 update tb set num = num + @value where id = @id and xtype = @xtype --@value是插入的num值,@id @xtype 是表中对应的id xtype --对没有在表中存在的id xtype可以直接插入 insert into tb select @id,@value,@xtype,@stime
------解决方案--------------------
4楼的不就是你想要的结果吗
------解决方案--------------------