从两个表中添加值并存储到第三个表中

时间:2016-06-07 05:37:39

标签: sql oracle11g

INSERT INTO Table1 (Amount, ContactName, State, City) 
values 
(
    (Select Amount from Table2 where id=12)+
    (Select Amount from Table3 where id=13),
    'Sam',Newyork,'Newyork'
);

我试图将Table2中金额的值存储为Table2 + Table3的总和Amount

2 个答案:

答案 0 :(得分:1)

尝试使用nvl(sum(Amount),0)SUM将汇总表格中的所有值,如果没有行,您将获得NULLNVL将移除可能的NULL,并将其替换为0

INSERT INTO Table1 (Amount, ContactName, State, City) 
values 
(
    (Select nvl(sum(Amount),0) from Table2 where id=12)+
    (Select nvl(sum(Amount),0) from Table3 where id=13),
    'Sam','Newyork','Newyork'
);

答案 1 :(得分:1)

你也可以尝试另一种方式:

INSERT INTO Table1 (Amount, ContactName, State, City) 
values 
(
     select sum(Amount) Amount
       from (Select Amount from Table2 where id=12
             union all
             Select Amount from Table3 where id=13),
    'Sam',Newyork,'Newyork'
);