2017-02-15 65 views
1

在每一行中,我有一列數量(float)和id(int)。所以,我想用連接將庫存中table1到table2數量相同的數量總和相加。例。用連接更新每個sql server行

我的SQL信息

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

我要總結從表1中的量,並加入到它在表中添加2

期望的結果表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 

我嘗試此代碼,但它只添加第一行

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

您的代碼加入的ID和項目ID,但你不顯示,你的表。 – manderson

回答

1

一個簡單連接和聚合應該做的伎倆

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) 
0

這應該做...

CREATE TABLE #table1 (id INT, quantities INT) 

INSERT INTO #table1(id, quantities) 
VALUES (1, 1) 
INSERT INTO #table1(id, quantities) 
VALUES (1, 2)  
INSERT INTO #table1(id, quantities) 
VALUES (2, 4)  
INSERT INTO #table1(id, quantities) 
VALUES (2, 1)  
INSERT INTO #table1(id, quantities) 
VALUES (3, 7)  

CREATE TABLE #table2 (id INT, quantities INT) 

INSERT INTO #table2(id, quantities) 
VALUES (1, 0) 
INSERT INTO #table2(id, quantities) 
VALUES (2, 0)  
INSERT INTO #table2(id, quantities) 
VALUES (3, 0) 

UPDATE #table2 
SET quantities = t1.quantities 
FROM #table2 t2 
    JOIN (
      SELECT id, SUM(quantities) AS quantities 
      FROM #table1 
      GROUP BY id 
     ) t1 ON 
     t2.id = t1.id 

DROP TABLE #table1 
DROP TABLE #table2