SQL Server 2008 R2
I am going to explain it as simple as possible. Now I have a
table_1
which has price
and itemId
. I also have another table table_2
which has totalprice,itemId
.What I want to do is to sum all
price
from table_1
grouped by itemId
and update that sum of price in table_2
with itemId
key as the common column. The price per
itemId
summed from table_1
should update the totalprice
column in table_2
You can do like this:
You can do like this:
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
If you don't already have all itemid's in table_2 you can use a merge to update the existing rows and add a new row if it is missing.
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);
I love MSSQL
No comments:
Post a Comment