tags:

views:

56

answers:

3

Hi.

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
+3  A: 

You can use a GROUP BY query to achieve this:

select CustomerID, count(*) as NumDuplicates
from Customer
group by CustomerID
having count(*) > 1
RedFilter
Also there is a success flag in the Orders table. I would like to get all the rows by customerID where orders table success flag is 1.
nav100
@nav100: You should update the question and add this new requirement. It changes the query.
FrustratedWithFormsDesigner
A: 
select CustomerID, count(1)
  from Customer
 group by CustomerID
having count(1) > 1
Pablo Santa Cruz
@OMG Ponies: actually, this is counting the constant 1 not ordinal... (at least in SQL Server). In addition, what would SUM(1) do?
gbn
@OMG Ponies: 1 is used as a constant here.
Pablo Santa Cruz
Sorry, thought it was ordinal notation. I always use columns or *...
OMG Ponies
A: 

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; 
FrustratedWithFormsDesigner
Here is the query I came up with. But it's 2 queries.select customerID from Customerselect * from Orders where orderID in (select OrderId from Customer where customerID = 123456) and success = 1
nav100