在每一行中,我有一个列数量(float)和id(int)。所以我想通过联接来添加库存中table1到table2数量相同id的数量总和。实施例。
我的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 :(得分:1)
简单的JOIN和聚合应该可以解决问题
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)
答案 1 :(得分: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