日期:2014-05-18 浏览次数:20590 次
select sum(cnt) from 表2 where sldat between '2011-01-01' and '2012-12-31'
declare @basvipnew table (vipid int,vipname varchar(5),rest int) insert into @basvipnew select 1,'tom',0 union all select 2,'name',1 union all select 3,'jerry',1 declare @basvipcnt table (vipid int,cnt int,sldat datetime) insert into @basvipcnt select 1,5,'2011-03-01' union all select 1,6,'2011-02-03' union all select 2,1,'2011-09-08' union all select 2,10,'2011-11-01' union all select 3,2,'2011-08-07' declare @basvipuse table (vipid int,cnt int,sldat datetime) insert into @basvipuse select 1,-3,'2011-03-01' union all select 1,-7,'2011-02-03' union all select 2,-12,'2011-09-08' union all select 2,-10,'2011-11-01' union all select 3,-22,'2011-08-07' update @basvipnew set rest=b.cnt+c.cnt from @basvipnew a left join (select vipid,sum(cnt) as cnt from @basvipcnt where sldat between '2011-01-01' and '2011-12-31' group by vipid) b on a.vipid=b.vipid left join (select vipid,sum(abs(cnt)) as cnt from @basvipuse where sldat between '2011-01-01' and '2011-12-31' group by vipid) c on a.vipid=c.vipid select * from @basvipnew /* vipid vipname rest ----------- ------- ----------- 1 tom 21 2 name 33 3 jerry 24 */ /* 如果正负积分都加的话,用绝对值就ok了。 如果正的是减,负的是加,sum然后求相反数就ok了。 */