2012-12-04 11 views
0

我是新來的,因爲我在學習SQL,而且遇到了一個我無法解決的問題。請幫幫我。 我有兩個表結果和收入與數據,看到表的截圖。 https://www.box.com/s/5c1ah5qi9jg5ty499wvs如何連接表格而不是重複數據

我想加入這些表格,但由於carthesian產品的某些數據被添加了兩次。這裏是我的代碼:

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 

有什麼建議嗎?提前致謝。

G.

+0

你爲什麼試圖聯合這兩個表?你能提供你想要的輸出樣本嗎?點域代表什麼? –

+1

你可以請我讓這個場景需要的o/p? –

+0

@ coge.soft這裏是正確輸出的鏈接。 https://www.box.com/s/enj1sfnkdrib357tao1p – giecze

回答

1

我想你想要的是一個full outer join,而不是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) 

或者,你可能想要做的兩個表之間的union,然後彙總,如:

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的多行,該版本也能正常工作e組合。

+0

第二個解決方案完成了這項工作。謝謝。在第一個解決方案中,仍有重複的(添加了兩次)記錄。 – giecze

相關問題