代码之家  ›  专栏  ›  技术社区  ›  Patriots299

SQL查询帮助-重复值

sql
  •  0
  • Patriots299  · 技术社区  · 7 年前

    假设我有下表: 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 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    你似乎想要:

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

    即,显示发票上有多个客户的发票。

        2
  •  0
  •   chris    7 年前

    通过首先查找出现在1个以上客户的所有发票号码,构建此查询对我来说是最清楚的:

    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