如何只返回多次内连接的行

时间:2009-08-27 04:01:04

标签: sql sql-server join

我有两张桌子,一张用于发票,另一张用于收款。收款可以通过外键加入发票,如下所示:

from invoices t1 inner join incoming_payments t2 on t1.receiptnum = t2.docnum

问题:我想要退回所有发票,这些发票上贴有多张付款。对于每张发票,我想要返回其docnum,这只是发票的唯一ID。

以下是我尝试过的一些不起作用的事情:

select t0.docnum
from invoices t0 inner join incoming_payments t1 on t0.receiptnum = t1.docentry 
group by t0.docnum
having count(t0.docnum) > 1  

select t0.docnum
from invoices t0 inner join incoming_payments t1 on t0.receiptnum = t1.docentry
group by t0.receiptnum, t0.docnum
having count(t0.receiptnum) > 1

有什么想法吗?

5 个答案:

答案 0 :(得分:1)

我不确定为什么第一个不起作用......真的应该这样。你可以扩展“它不起作用”吗?

尝试:

select t0.docnum, *
from invoices t0 
  inner join incoming_payments t1 on t0.receiptnum = t1.docentry 

select t0.docnum, count(*)
from invoices t0 
  inner join incoming_payments t1 on t0.receiptnum = t1.docentry 
group by t0.docnum

帮助您弄清楚发生了什么。

罗布

答案 1 :(得分:1)

select t0.docnum, count(*)
from invoices t0 inner join incoming_payments t1 on t0.receiptnum = t1.docentry 
group by t0.docnum
having count(*) > 1

答案 2 :(得分:1)

你得到什么SQL错误?您是否按要求分组的所有字段进行分组?

答案 3 :(得分:0)

我认为您的示例SQL不一致(与您提供的第一个SQL相比) 即在第一个SQL中,您使用docnum进行比较,在后续SQL中,您使用的是docentry。

select t0.docnum, count(t1.*)
from invoices t0 inner join incoming_payments t1 on t0.receiptnum = t1.docentry
group by t0.docnum
having count(t1.*) > 1

编辑:比较的匹配字段是什么?
t0.receiptnum = t1.docnumt0.receiptnum = t1.docentry

EDIT2:请参阅上面修改过的SQL。

答案 4 :(得分:0)

鉴于我正在使用的架构,答案最终会变得复杂得多。我没有在这里包含实际代码,但我刚才解决了这个问题。只是想跟进并感谢大家的帮助。