协助进行SQL查询-重复值

时间:2018-08-07 01:53:35

标签: sql

假设我有下表: https://i.stack.imgur.com/ymYRX.png

请注意,有些客户使用相同的发票编号。

我希望有一个SQL查询,该结果将显示客户和客户之间相等的发票。

我尝试了类似的方法(当然它没有用):

SELECT Customer, Invoice_Number, Invoice_Amount
FROM CUSTOMER_TABLE
WHERE (Customer = Fred)||Invoice_Number = (Customer = Alan)||Invoice_Number

预期结果将是: https://i.stack.imgur.com/rGNF1.png

2 个答案:

答案 0 :(得分:0)

您似乎想要:

select t.*
from t
where exists (select 1
              from t t2
              where t2.invoice_number = t.invoice_number and
                    t2.customer <> t.customer
             );

也就是说,显示发票上有多个客户的发票。

答案 1 :(得分:0)

对于我来说,最简单的方法是首先查找为多个客户显示的所有发票编号:

select Invoice_Number from CUSTOMER_TABLE 
group by Invoice_Number having count(*) > 1;

 Invoice_Number 
----------------
 AB111

现在,使用where子句中的上述查询来查找包含其中一个发票编号的每一行,用于:

select * from CUSTOMER_TABLE 
where Invoice_Number in (
   select Invoice_Number from CUSTOMER_TABLE 
   group by Invoice_Number having count(*) > 1
);

 Customer | Invoice_Number
----------+---------------
 Fred     | AB111
 Fred     | AB111
 Alan     | AB111
 Alan     | AB111
 Alan     | AB111