2012-12-04 2 views
0

저는 SQL을 배우면서 새로운 문제가 있습니다. 해결할 수없는 문제가 발생했습니다. 도와주세요. 결과 및 결과가있는 두 개의 테이블이 있습니다. 표 스크린 샷을 참조하십시오. https://www.box.com/s/5c1ah5qi9jg5ty499wvs테이블을 조인하고 데이터를 복제하지 않는 방법

이 테이블에 가입하고 싶지만 카티 션 제품으로 인해 일부 데이터가 두 번 추가되고 있습니다. 여기 내 코드는 다음과 같습니다.

select o.point, o.date, sum(out), sum(inc) from outcome o left join income i on o.point=i.point and o.date=i.date 
group by o.point, o.date 
union 
select i.point, i.date, sum(out), sum(inc) from income i left join outcome o on o.point=i.point and o.date=i.date 
group by i.point, i.date 

어떤 조언이 있습니까? 미리 감사드립니다. 당신이 같이 집계 다음 두 테이블 사이에 union을하고 싶은, 그리고 수도 또는

select coalesce(o.point, i.point) as point, 
     coalesce(o.date, i.date) as date, 
     sum(out), sum(inc) 
from outcome o full outer join 
    income i 
    on o.point=i.point and o.date=i.date 
group by coalesce(o.point, i.point) , coalesce(o.date, i.date) 

:

는 G.는

+0

왜이 두 테이블을 결합하려고합니까? 원하는 출력 샘플을 제공 할 수 있습니까? 포인트 필드는 무엇을 나타 냅니까? –

+1

이 시나리오에서 필요한 o/p를 알려 주실 수 있습니까? –

+0

@ coge.soft 여기에 올바른 출력 링크가 있습니다. https://www.box.com/s/enj1sfnkdrib357tao1p – giecze

답변

1

나는 당신이 원하는 것은 full outer join 오히려 union (A)보다 생각 :

select point, date, sum(out), sum(inc) 
from ((select o.point, o.date, out, NULL as inc 
     from outcome 
    ) union all 
     (select i.point, i.date, NULL as out, inc 
     from income 
    ) 
    ) io 
group by point, date 

주어진 지점/dat에 대해 각 테이블에 여러 행이 있어도이 버전이 올바르게 작동합니다. 전자 조합.

+0

두 번째 해결책이 효과가있었습니다. 감사. 첫 번째 해법에서 여전히 중복 기록 (2 번 추가)이있었습니다. – giecze

관련 문제