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。

4

1 回答 1

1

我认为你想要的是 afull outer join而不是 a 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在两个表之间执行 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

即使每个表中针对给定的点/日期组合有多行,此版本也将正常工作。

于 2012-12-04T14:49:39.257 回答