我有两张桌子,
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。
答案 0 :(得分:4)
使用Union all
结合两个选择查询和sum
value
与group 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