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

**************急! 帮帮忙,更新同一张表!************
有这样一张表:   要求按TheID
更新   ItemCode=9   的项=(     ItemCode为8的项-   ItemCode为10+11的项)

TheID       ItemCode     TheValue
001               10                 1
001               11                 2
001                 8                 5
001                 9                 1
002               10                 2
002               11                 3
002                 8                 6
002                 9                 1
结果如下
001               10                 1
001               11                 2
001                 8                 5
001                 9                 2
002               10                 2
002               11                 3
002                 8                 6
002                 9                 1


------解决方案--------------------
declare @t table(TheID varchar(10),ItemCode int,TheValue int)
insert @t
select '001 ', 10, 1 union all
select '001 ', 11, 2 union all
select '001 ', 8, 5 union all
select '001 ', 9, 1 union all
select '002 ', 10, 2 union all
select '002 ', 11, 3 union all
select '002 ', 8, 6 union all
select '002 ', 9, 1

update a set
TheValue = (select TheValue from @t where TheID = a.TheId and ItemCode=8)-
((select TheValue from @t where TheID = a.TheId and ItemCode=10) +
(select TheValue from @t where TheID = a.TheId and ItemCode=11))
from @t as a where ItemCode = 9

select * from @t

/*
结果TheID ItemCode TheValue
---------- ----------- -----------
001 10 1
001 11 2
001 8 5
001 9 2
002 10 2
002 11 3
002 8 6
002 9 1
*/