0

私は SQL を学んでいて、解決できない問題に遭遇しました。私を助けてください。Outcome と Income の 2 つのテーブルとデータがあります。テーブルのスクリーンショットを参照してください。 https://www.box.com/s/5c1ah5qi9jg5ty499wvs

これらのテーブルを結合したいのですが、デカルト積のために一部のデータが 2 回追加されています。これが私のコードです:

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.

4

1 に答える 1

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に、2つのテーブル間で実行してから、集計することもできます。

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

このバージョンは、特定のポイントと日付の組み合わせに対して各テーブルに複数の行がある場合でも、正しく機能します。

于 2012-12-04T14:49:39.257 に答える