Search code examples
sql-serversql-server-2014

Update each sql server row with join


In each row, i have one column quantities(float) and id(int). So I want with the join to add the sum of quantities with the same id from table1 to table2 quantities in inventory. Example.

My SQL information

    Table 1                   Table 2
 id   quantities           id    quantities
 1        1                 1         0  
 1        2                 2         0
 2        4                 3         0 
 2        1         
 3        7

I want to sum quantities from table 1 and with join to add it in table 2

Desired result to table 2

    Table 1                   Table 2
 id   quantities           id    quantities
 1        1                 1         3  
 1        2                 2         5
 2        4                 3         7
 2        1         
 3        7

I'm trying this code, but it adds only first row

update i set quantities=i.quantities+sum(s.rent) from inventory i join temp_rent s on i.id=s.itemid

Solution

  • A simple JOIN and aggregation should do the trick

    Update Table2
       set quantities = B.Total
     From  Tabel2 A
     Join (Select ID
                 ,Total=sum(quantities)
           From  Table1
           Group By ID
          ) B
      on (A.ID=B.ID)