表1:
ID Total1 Total2 Total3
1 10 0 20
1 40 0 50
1 15 0 5
表2:
ID Total
1 140
如何累加所有行并在table2中找到匹配的总数?
如何累加所有行并在table2中找到NOT匹配的总数并写入update语句来更新(添加那些)并写入table2?
select sum(t1.total1) + sum(t1.total2) +sum(t1.total3) as "Total" from
table t1, table t2 where t1.ID=t2.ID and sum(t1.total1) +
sum(t1.total2) +sum(t1.total3)=t2.total;
我无法正确理解更新语法。
答案 0 :(得分:1)
看起来您有正确的查询来查找总计并将其匹配。要更新总数不同的行,可以使用相关的子查询,如下所示:
UPDATE table2
SET total = (
SELECT SUM(Total1 + Total2 + Total3) FROM table1
WHERE id = table2.id
GROUP BY id
)
或者使用连接(稍微复杂一些,但可能更快)
UPDATE t2
SET t2.total = t1.total
FROM table2 t2
INNER JOIN (
SELECT id, SUM(Total1 + Total2 + Total3) as total FROM table1
GROUP BY id
) t1 ON t1.id = t2.id
WHERE t2.total <> t1.total
答案 1 :(得分:0)
select T1.* from
(
select t1.ID, sum(t1.total1) + sum(t1.total2) + sum(t1.total3) as Total
from table t1
group by t1.ID
) t1
inner join table t2 on t1.ID = t2.ID and t1.Total = t2.total