1. 양쪽 테이블의 기준컬럼을 중심으로 집계컬럼이 동일한 경우
WITH
A AS
(SELECT 'A' AS CODE, 8 AS QTY FROM DUAL
UNION ALL
SELECT 'A' AS CODE, 2 AS QTY FROM DUAL
UNION ALL
SELECT 'B' AS CODE, 7 AS QTY FROM DUAL
UNION ALL
SELECT 'D' AS CODE, 9 AS QTY FROM DUAL)
, B AS
(SELECT 'A' AS CODE, 8 AS QTY FROM DUAL
UNION ALL
SELECT 'C' AS CODE, 7 AS QTY FROM DUAL
UNION ALL
SELECT 'C' AS CODE, 2 AS QTY FROM DUAL
UNION ALL
SELECT 'D' AS CODE, 9 AS QTY FROM DUAL)
SELECT T.CODE
, SUM(T.QTY) AS QTY
FROM (SELECT CODE
, QTY
FROM A
UNION ALL
SELECT CODE
, QTY
FROM B) T
GROUP BY T.CODE
ORDER BY T.CODE;
CODE QTY
-------------------------------- ----------
A 18
B 7
C 9
D 18
2. 양쪽 테이블의 기준컬럼을 중심으로 집계컬럼이 상이한 경우
WITH
A AS
(SELECT 'A' AS CODE, 8 AS QTY FROM DUAL
UNION ALL
SELECT 'A' AS CODE, 2 AS QTY FROM DUAL
UNION ALL
SELECT 'B' AS CODE, 7 AS QTY FROM DUAL
UNION ALL
SELECT 'D' AS CODE, 9 AS QTY FROM DUAL)
, B AS
(SELECT 'A' AS CODE, 8 AS QTY FROM DUAL
UNION ALL
SELECT 'C' AS CODE, 7 AS QTY FROM DUAL
UNION ALL
SELECT 'C' AS CODE, 2 AS QTY FROM DUAL
UNION ALL
SELECT 'D' AS CODE, 9 AS QTY FROM DUAL)
SELECT T.CODE
, SUM(T.A_QTY) AS A_QTY
, SUM(T.B_QTY) AS B_QTY
FROM (SELECT CODE
, QTY AS A_QTY
, TO_NUMBER(NULL) AS B_QTY
FROM A
UNION ALL
SELECT CODE
, TO_NUMBER(NULL) AS A_QTY
, QTY AS B_QTY
FROM B) T
GROUP BY T.CODE
ORDER BY T.CODE;
CODE A_QTY B_QTY
-------------------------------- ---------- ----------
A 10 8
B 7
C 9
D 9 9