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

潮起潮落 2014-10-13 08:37:39
表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了,这样可以减少操作影响的行数。

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

希望大家能不吝赐教,谢谢!
...全文
1235 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zaj50030 2017-07-06
  • 打赏
  • 举报
回复
UPDATE distribution_member AS a, (select uid, sum(invest) AS invest_sum FROM distribution_invest group by uid ) AS b SET a.invest_total=b.invest_sum where a.uid=b.uid
潮起潮落 2014-10-14
  • 打赏
  • 举报
回复
非常感谢诸位! 我对比下查询计划仔细看看,先结贴了。
wtujedp 2014-10-14
  • 打赏
  • 举报
回复
看看这个行不?
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
xiaodongni 2014-10-13
  • 打赏
  • 举报
回复
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 忘了最好的条件了
xiaodongni 2014-10-13
  • 打赏
  • 举报
回复
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 表里面的数据结构把。贴出来看看更好些点。
还在加载中灬 2014-10-13
  • 打赏
  • 举报
回复
你参考一下吧
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

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧