/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Wednesday, July 24, 2013

SQL Server - Select Multiple Rows Data From One Table And Update Multiple Rows Data On Another Table With First Selected Data


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

My Blog List

  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
    10 years ago