Reputation: 1869
I know how to query to find records with duplicate records based on a field or fields e.g.
Select Customer,Count(*) from Table1 group by Customer,Month having count(*)>1
which would give me a list of all customers who ordered more than once in a given month.
However from that select I'd like to:
Refine the group to show only dupes where the product is DIFFERENT. I know if I wanted to do the same I'd simple add to group by ',Product'
but in my case it is Product != Product
and I'm not sure how to indicate that in the group
Instead of getting a list of just which Customers ordered more than one product in a given month a list of all those orders. In other words instead of this type of list from the group:
Bob,December Mary,June
I am trying to return:
Bob,Widget,December
Bob,Pipes,December
Mary,Books,June
Mary,Cars,June
Upvotes: 0
Views: 34
Reputation: 34294
If product field is in the same table, then you can use count with distinct on the product field to get the number of distinct products:
Select Customer, Month, Count(distinct product)
from Table1
group by Customer, Month
having count(distinct product)>1
If you want to know what they ordered, then join it back as a subquery to your main table:
select distinct t1.customer, t1.month, t1.product from table1 t1
inner join
(Select Customer, Month, Count(distinct product)
from Table1
group by Customer, Month
having count(distinct product)>1
) t2 on t1.customer=t2.customer and t1.month=t2.month
The distinct in the outer select depends on your exact needs.
Upvotes: 1