2016-07-19 1 views
1

병합 할 테이블이 여러 개인 경우이 테이블의 ID 값이 다를 수 있습니다.테이블 병합 및 모든 고유 ID 값 유지

표 1 :

ID Year Month Size2 
A 2015 4 20 
C 2015 5 40 

표 3 :

ID Year Month Size3 
D 2015 6 50 
E 2015 7 50 

내가 병합 된 표는 다음과 같이 할 2

ID Year Month Size1 
A 2015 4 10 
B 2015 5 20 

표 예를 들어

:

ID Year Month Size1 Size2 Size3 
A 2015 4  10 20 NULL 
B 2015 5  20 NULL NULL 
C 2015 5 NULL 40 NULL 
D 2015 6 NULL NULL 50 
E 2015 7 NULL NULL 50 

출력 ID 열에 모든 테이블의 모든 고유 ID를 포함 시키길 원합니다. 내 생각 엔이 방법은 Full Outer Join On ID를 사용하여 얻을 수 있지만 원하는 출력 형식을 생성 할 수 없다는 것입니다.

답변

0

가 여기에 표시 결과를 줄 것이다 또 다른 가능한 쿼리 : SELECT t.id, t.year, t.month, :

SELECT t.id, t.year, t.month, 
    SUM(size1) AS size1, SUM(size2) AS size2, SUM(size3) AS size3 
FROM (
    SELECT id, year, month, size1, NULL AS size2, NULL AS size3 FROM t1 
    UNION ALL 
    SELECT id, year, month, NULL, size2, NULL FROM t2 
    UNION ALL 
    SELECT id, year, month, NULL, NULL, size3 FROM t3 
) AS t 
GROUP BY t.id, t.year, t.month; 
+0

빌, 당신의 접근 방식은 작은 변화와 함께 작동 SUM (t.size1) AS 크기 1, SUM (t.size2) AS 크기 2, SUM (t.size3) AS 크기 3 FROM ( SELECT ID, 연도, 월, 크기 1, NULL AS 크기 2, NULL AS 크기 3 FROM t1 UNION ALL SELECT id, 년, 월, NULL AS size1, size2, NULL as size3 FROM t2 UNION ALL SELECT ID, 연도, 월, NULL AS 크기 1, NULL AS 크기 2, 크기 3 FROM t3 GROUP BY t.id, t.year, t.month; 감사합니다. – ohmyan

+0

적용된 수정, 감사합니다! –

0
select t1.id, t1.year, t1.month, t1.size1, t2.size2, t3.size3 
from table1 as t1 
left outer join table2 as t2 on t1.id = t2.id and t1.year = t2.year and t1.month = t2.month 
left outer join table3 as t3 on t1.id = t3.id and t1.year = t3.year and t1.month = t3.month 
union 
select t3.id, t3.year, t3.month, t1.size1, t2.size2, t3.size3 
from table3 as t3 
left outer join table1 as t1 on t3.id = t1.id and t3.year = t1.year and t3.month = t1.month 
left outer join table2 as t2 on t3.id = t2.id and t3.year = t2.year and t3.month = t2.month