2012-05-09 121 views
-1

表1:累積條件查詢

ID  Total1 Total2 Total3 
1   10  0   20 
1   40  0   50 
1   15  0   5 

表2:

ID  Total 

1  140 

如何添加累計所有的行,並找到在表2的匹配總?

我該如何累加所有行並在table2中找到不匹配的總數,然後編寫更新語句來更新(添加這些)並寫入到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

你缺少那裏有一個「GROUP BY ID」,不是嗎? –

+0

這是功課嗎? – Tejs

+0

你能描述一下查詢應該在你提交的場景中做什麼(預期的輸出是什麼)? – GolfWolf

回答

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