2012-12-04 14 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

相关问题