SQL query with duplicate records

前端 未结 3 1878
走了就别回头了
走了就别回头了 2021-01-12 15:39

I am trying to write a query in SQL server to find out if there are any multiple rows for each customer by customerID. Please let me know.

Here is the table structur

相关标签:
3条回答
  • 2021-01-12 16:26

    You can use a GROUP BY query to achieve this:

    select CustomerID, count(*) as NumDuplicates
    from Customer
    group by CustomerID
    having count(*) > 1
    
    0 讨论(0)
  • 2021-01-12 16:27

    To see how many of each customer you have:

    SELECT COUNT(*), CustName, CustomerID
    from Customer
    Group by CustName, CustomerID
    

    You can use a having clause to limit to just duplicates:

    SELECT COUNT(*), CustName, CustomerID
    from Customer
    Group by CustName, CustomerID
    having count(*) > 1
    

    UPDATE

    To get those with successful orders:

    select count(*), CustName, CustomerID
    from(
      SELECT CustName, CustomerID
      from Customer, orders
      where customer.orderID = orders.orderID
      and orders.success = 1) subquery
    group by subquery.CustName, subquery.CustomerID
    having count(*) > 1; 
    
    0 讨论(0)
  • 2021-01-12 16:42
    select CustomerID, count(1)
      from Customer
     group by CustomerID
    having count(1) > 1
    
    0 讨论(0)
提交回复
热议问题