我将尽可能简单地解释它。现在我的table_1
有price
和itemId
。我还有另一张表table_2
totalprice,itemId
。
我想要做的是将price
中的所有table_1
与按itemId
分组的table_2
相加,并将itemId
中的价格总和更新为itemId
共同专栏。
table_1
总计totalprice
的价格应更新table_2
中的{{1}}列。
这可能吗?谢谢。
SQL Server 2008 R2
答案 0 :(得分:3)
是的,这是可能的。你可以这样做:
update T2
set totalprice = T1.totalprice
from Table_2 as T2
inner join (select sum(price) as totalprice,
itemid
from Table_1
group by itemid) as T1
on T2.itemid = T1.itemid
http://data.stackexchange.com/stackoverflow/q/119388/
如果您还没有table_2中的所有itemid,则可以使用merge更新现有行,如果缺少则添加新行。
merge Table_2 as T2
using (select sum(price) as totalprice,
itemid
from Table_1
group by itemid) as T1
on T1.itemid = T2.itemid
when matched then
update set totalprice = T1.totalprice
when not matched then
insert (totalprice, itemid)
values(T1.totalprice, T1.itemid);