问题描述
我有2张桌子
X
-----------------
id | value
1 | 10
2 | 20
Y
----------------
id | value
2 | 30
那么输出应该是
result
-----------------
id | value
1 | 10
2 | 50 (20 + 30) from both the tables
我必须在蜂巢中做。
解决方法
这看起来像left join
:
select x.id,(x.value + coalesce(y.value,0)) as value
from x left join
y
on x.id = y.id
,
您可以在UNION ALL和GROUP BY-
中尝试以下选项SELECT id,SUM(value) Value
FROM
(
SELECT id,value FROM X
UNION ALL
SELECT id,value FROM Y
) A
GROUP BY id
,
如果两个表的ID列表都不匹配,我们可以使用完全外部联接获取结果。请考虑以下查询:
select x.id,NVL(x.value,0)+NVL(y.value,0) value from x full outer join y on x.id=y.id;