合并两个表,总结值

时间:2015-02-07 01:08:19

标签: sql oracle select

我有两张桌子,

Table1

Key, Value
----------
1     10
2     20
3     30

Table2

Key, Value
----------
3     30
4     40
5     50

如何合并它们并使用SQL获取以下内容?

Desired output

Key, Value
----------
1     10
2     20
3     60
4     40
5     50

Python 术语中,我猜它被称为总结两个词典。

PS:我正在使用Oracle 12c。

2 个答案:

答案 0 :(得分:4)

使用Union all结合两个选择查询和sum valuegroup by键列

select key,sum(value) value
from 
(
select Key, Value from table1
union all
select Key, Value from table2
) a
group by key

或使用Full outer Join

SELECT COALESCE(a.Key, b.key),
       COALESCE(a.Value, 0) + COALESCE(b.value, 0)
FROM   table1 a
       FULL OUTER JOIN Table2 b
                    ON a.Key = b.Key

答案 1 :(得分:2)

为了提高速度,请尽可能避免使用UNION/UNION ALL。请尝试以下答案:

SELECT 
      NVL(A.Key,B.Key)[Key],
     (NVL(A.Value,0) + NVL(B.Value,0))[Value] 
FROM Table1 A
FULL JOIN Table2 B ON A.Key=B.Key