检索重复项列表

时间:2018-10-03 18:10:30

标签: sql sql-server

我正在尝试检索包含多个具有相同项目IDS的行项目的发票清单。我没有要查找的特定项目,我只是想找到一种方法来从发票明细表中检索行,该行包含与发票表相同的发票编号,并且在发票明细中具有多个相同项目的行表。希望如此描述似乎有点难以理解,但任何建议都将不胜感激!谢谢大家。

这些子查询不正确,但希望它将对我要做什么有所了解:

SELECT Invoice.InvNum, Invoice.Invdate, Invoice.Description
FROM Invoice 
INNER JOIN InvDetail ON (Invoice.InvNum = InvDetail.InvoiceNumber) 
WHERE Invoice.InvDate > '7/3/2018' AND ItemID NOT IN  
      (SELECT ItemID FROM InvDetail 
       GROUP BY ItemID HAVING COUNT(DISTINCT ItemID) > 1)
ORDER BY InvDetail.InvoiceNumber


SELECT Invoice.InvNum, Invoice.Invdate, Invoice.Description
FROM Invoice 
INNER JOIN InvDetail ON (Invoice.InvNum = InvDetail.InvoiceNumber) 
WHERE Invoice.InvDate > '7/3/2018' AND InvDetail.InvoiceNumber IN  
     (SELECT InvoiceNumber FROM InvDetail 
      WHERE InvDetail.ItemID NOT IN 
           (SELECT ItemID FROM InvDetail GROUP BY ItemID HAVING COUNT (itemid) > 1))
ORDER BY Invoice.InvNum

1 个答案:

答案 0 :(得分:2)

您的子查询与发票不相关,JOIN可能导致检索同一张发票的多行。

据我所知,一个解决方案是使用EXISTS进行关联,聚合的子查询。

SELECT i.invnum,
       i.invdate,
       i.description
       FROM invoice i
       WHERE i.invdate > '7/3/2018'
             AND EXISTS (SELECT 1
                                FROM invoicedetail id
                                WHERE id.invoicenumber = i.invnum
                                GROUP BY id.itemid
                                HAVING count(id.itemid) > 1);