Oracle-10g
根據另一個表中的數據總和更新列
我有兩張桌子:
表 1 (col1, col2, col3, col4, val1, status) 表
2 (col1, col2, col3, col4, val2)
對於 Table1 和 Table2,列 (col1, col2, col3, col4) 是複合主鍵。
Table2 可能有重複的行,因此我想
group by (col1, col2, col3, col4)
和sum(val2)
之後,我想通過when
Table1.val1
的值進行更新。sum(Table1.val2)``Table1.col1 = Table2.col1 and Table1.col2 = Table2.col2 and Table1.col3 = Table2.col3 and Table1.col4 = Table2.col4 and status= 'V'
我做了這樣的事情:
UPDATE Table1 SET val1 = ( select t_sommevbrute.sumvalbrute from ( Select col1,col2,col3,col4,SUM(val2) sumvalbrute From Table2 Where col3 = 2014 And col2=51 And status= 'V' GROUP BY col1, col2, col3, col4 ) t_sommevbrute WHERE Table1.col1 = t_sommevbrute.col1 and Table1.col2 = t_sommevbrute.col2 and Table1.col3 = t_sommevbrute.col3 and Table1.col4 = t_sommevbrute.col4)
有人可以幫我嗎?謝謝
如果您有主鍵,則沒有重複的行。
在 Oracle 中,您使用 MERGE 而不是 UPDATE 來執行多表 UPDATE,因為那效率低下。
merge into table1 using (select col1, col2, col3, col4, sum(val2) sum_val2 from table2 group by col1, col2, col3, col4) table2 on (table1.col1 = table2.col1 and table1.col2 = table2.col2 and table1.col3 = table2.col3 and table1.col4 = table2.col4) when matched then update set table1.val1 = table2.sum_val2, table1.status = 'V';
如果 col1, col2, col3, col4 真的是複合主鍵,不需要 GROUP BY 和 SUM:
merge into table1 using table2 on (table1.col1 = table2.col1 and table1.col2 = table2.col2 and table1.col3 = table2.col3 and table1.col4 = table2.col4) when matched then update set table1.val1 = table2.val2, table1.status = 'V';