当前位置: 代码迷 >> Sql Server >> 怎样写一个Update语句可以联表sum后用结果值更新对应字段呢?该如何处理
  详细解决方案

怎样写一个Update语句可以联表sum后用结果值更新对应字段呢?该如何处理

热度:9   发布时间:2016-04-24 09:52:37.0
怎样写一个Update语句可以联表sum后用结果值更新对应字段呢?
表A是主表,有一个标识TID,有一个字段是Result
表A和表B是一对多,表B中存储TID和Num

现在需要sum所有表B中的Num,更新到表A对应TID的记录中Result字段。

我自己的写法如下,觉得相当繁琐,有没有更简化性能更高的写法呢?因为实际数据量还是比较大的。


update TableA
set Result = ISNULL
(
(select t.AllCount from
(
select 
P.TID,sum(P.Col1 * P.Col2) as AllCount
from
TableP P 
where 
P.X > 0
AND P.XX = 0
AND P.XXX = 1
AND P.XXX <> 23
group by P.TID
)
t
where t.TID = TableA.TID
)
,0)
where TID > 0


另外,在Update的同时能不能去判断=号右边的值(sum出来的值)为0/null(不加isnull的话,如果表B中没有TID对应的记录,得出的AllCount就为null了),然后为0/null的话就不Update了,这样可以减少操作影响的行数。

这个同样想不起如何来写。

希望大家能不吝赐教,谢谢!
------解决思路----------------------
你参考一下吧
UPDATE A
SET Result=ISNULL(T.Result,0)
FROM
TableA A JOIN
(
SELECT
A.TID,SUM(B.Col1 * B.Col2)Result
FROM
TableA A
LEFT JOIN TableP B ON A.TID=B.TID
GROUP BY
A.TID
)T ON A.TID=T.TID
WHERE
A.Result IS NULL

------解决思路----------------------
update tablea
set result =t.AllCount
from (select 
P.TID,sum(P.Col1 * P.Col2) as AllCount
from
TableP P 
where 
P.X > 0
AND P.XX = 0
AND P.XXX = 1
AND P.XXX <> 23
group by P.TID) as t join tablea as b
on t.tid=b.tid
试试这个, 看看你的tablea 表里面的数据结构把。贴出来看看更好些点。
------解决思路----------------------
update b
set result =t.AllCount
from (select 
P.TID,sum(P.Col1 * P.Col2) as AllCount
from
TableP P 
where 
P.X > 0
AND P.XX = 0
AND P.XXX = 1
AND P.XXX <> 23
group by P.TID) as t join tablea as b
on t.tid=b.tid
where b.tid>0
忘了最好的条件了
------解决思路----------------------
看看这个行不?
update TableA set result=t.AllCount
  from TableA a,
(
select 
P.TID,sum(P.Col1 * P.Col2) as AllCount
from
TableP P 
where 
P.X > 0
AND P.XX = 0
AND P.XXX = 1
AND P.XXX <> 23
group by P.TID
)t
where a.tid=t.tid and a.tid>0
  相关解决方案