我知道如何查询以基于一个或多个字段查找具有重复记录的记录,例如
Select Customer,Count(*) from Table1 group by Customer,Month having count(*)>1
这将为我提供在给定月份内多次订购的所有客户的列表。
但是从该选择中我想:
优化组以仅显示产品不同的愚人。我知道如果我想做同样的事情,我会简单地添加到 group by
',Product'
但在我的例子中它是Product != Product
而我不是确定如何在组中表明这一点获取所有订单的列表,而不是仅获取在给定月份内订购了多种产品的客户的列表。换句话说,而不是来自组的此类列表:
鲍勃,十二月 玛丽,六月
我正在尝试返回:
Bob,Widget,December
Bob,Pipes,December
Mary,Books,June
Mary,Cars,June
最佳答案
如果产品字段在同一个表中,那么您可以在产品字段上使用 count 和 unique 来获取不同产品的数量:
Select Customer, Month, Count(distinct product)
from Table1
group by Customer, Month
having count(distinct product)>1
如果您想知道他们订购了什么,请将其作为子查询连接回您的主表:
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
外部选择的不同取决于您的具体需求。
关于mysql - 查找具有不同值的重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504392/