Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with duplicate records

Tags:

sql

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 structure

Customer table
-----------------------------------------
orderID          CustName      CustomerID
---------------------------------------
100               test           123456    
101               test           123456

Orders table
------------------------------------
pID               OrderID
-----------------------------------
1                 100        
2                 101
like image 326
nav100 Avatar asked Jun 30 '10 18:06

nav100


2 Answers

You can use a GROUP BY query to achieve this:

select CustomerID, count(*) as NumDuplicates
from Customer
group by CustomerID
having count(*) > 1
like image 184
D'Arcy Rittich Avatar answered Sep 28 '22 06:09

D'Arcy Rittich


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; 
like image 24
FrustratedWithFormsDesigner Avatar answered Sep 28 '22 07:09

FrustratedWithFormsDesigner