我想更新table1的所有字段,它们引用表2中的相等字段,并且它是:sum: 示例:table1具有
Fieldname | amount
-------------------------
a | 200
a | 300
b | 50
b | 150
现在我想将Fieldname相等的金额之和复制到table2的相关字段中,所以它在表2中看起来像
Fieldname | SumAmount
-------------------------
a | 500
b | 200
答案 0 :(得分:1)
如果table2中已存在fieldNames,您可以执行以下操作:
UPDATE table2 t2
INNER JOIN
(SELECT fieldName, SUM(amount) as total
FROM table1
GROUP BY fieldName
) T1 ON t1.fieldName = t2.fieldName
SET t2.sumAmount = t1.total
否则,您必须INSERT:
INSERT INTO table2 (fieldName,sumAmount)
SELECT fieldName, SUM(amount)
FROM table1
GROUP BY fieldName
答案 1 :(得分:0)
试试这个:
INSERT INTO table2(Fieldname, SumAmount)
SELECT Fieldname, SUM(amount)
FROM table1
GROUP BY Fieldname;
答案 2 :(得分:0)
UPDATE table2 SET SumAmount=
(SELECT SUM(amount) FROM table1 GROUP BY fieldname)x
WHERE table2.fieldname=x.fieldname
答案 3 :(得分:0)
UPDATE table1 t1
SET
t1.amount = t2.SumAmount
INNER JOIN table2 t2 ON t1.Fieldname = t2.Fieldname