日期:2014-05-19  浏览次数:20556 次

给分 简单相加问题100分,最好一句update搞定
简单相加问题100分,最好一句update搞定

------解决方案--------------------
楼主这问题提的~~~~~~
------解决方案--------------------
--update,效率会高一点
create table #t (id int ,valF int,varT int)
insert #t
select 1,0,50 union
select 2,0,0 union
select 3,0,0 union
select 4,0,0 union
select 5,0,0

create table #t1(id int,addnum int)
insert #t1
select 1,10 union
select 2,12 union
select 3,13 union
select 4,17 union
select 5,30

declare @varT int,@valF int
select @varT = 0,@valF = varT from #t where id = 1

update _t
set @varT = @valF,@valF = _t1.addnum + @varT
,_t.varT = @varT,_t.valF = @valF
from #t _t
join #t1 _t1 on _t.id = _t1.id

select * from #t

id valF varT
----------- ----------- -----------
1 60 50
2 72 60
3 85 72
4 102 85
5 132 102

(所影响的行数为 5 行)


drop table #t,#t1

------解决方案--------------------
libin_ftsafe(子陌红尘:当libin告别ftsafe) ( ) 信誉:105 Blog 2007-03-09 15:28:10 得分: 0


--换一种写法,同样用一条SQL实现UPDATE
create table #t (id int ,valF int,varT int)
insert #t
select 1,0,50 union
select 2,0,0 union
select 3,0,0 union
select 4,0,0 union
select 5,0,0
create table #t1(id int,addnum int)
insert #t1
select 1,10 union
select 2,12 union
select 3,13 union
select 4,17 union
select 5,30
go

update a
set
valF=(select sum(varT) from #t where id <=a.id)+isnull((select sum(addnum) from #t1 where id <=a.id),0),
varT=(select sum(varT) from #t where id <=a.id)+isnull((select sum(addnum) from #t1 where id < a.id),0)
from
#t a
go

select * from #t
/*
id valF varT
----------- ----------- -----------
1 60 50
2 72 60
3 85 72
4 102 85
5 132 102
*/

drop table #t,#t1
go


-------

這個不可以?
------解决方案--------------------
UP!!
------解决方案--------------------
declare @i int
select top 1 @i=varT from #t order by id

select a.id,(select sum(addnum) from #t1 where id <=a.id)+@i
,isnull((select sum(addnum) from #t1 where id <a.id),0)+@i
from #t a
------解决方案--------------------
子陌兄,这里有你的盗版,改了封面~~~~~~~哈哈
------解决方案--------------------
我来啦。
------解决方案--------------------
呵呵,这边居然涨到200分了,占个楼层看看。
------解决方案--------------------
子陌兄,这里有你的盗版,改了封面~~~~~~~哈哈

----------------------------------

汗,盗版不会是说我吧?

不好意思,同事的贴子,我看都没看别人的回复就贴代码了。




呵呵,这边居然涨到200分了,占个楼层看看。

----------------------------

反正楼主分多,这200分是我加的,呵。。。



------解决方案--------------------
汗一个,楼上的强,盗用别人的ID?
汗一个,楼上的强盗,用别人的ID?