mysql - 查找具有不同值的重复记录

标签 mysql group-by

我知道如何查询以基于一个或多个字段查找具有重复记录的记录,例如

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/

相关文章:

python - 通过另一列 pandas 找到列组的最大值

mysql - 按 X 天的范围分组

MySQL JOIN 多个查询结果到 1 个结果集

java - 如何使用java为MySQL启用LDAP连接?

php - 如何在php中提交数据后重新加载页面功能

MySQL - 我应该如何索引这个表?

Mysql Group By 24小时间隔

mysql - 将 select 的结果返回到一个变量 MYSQL

javascript - 如何在组合框 DHTMLX 调度程序中获取事件名称

php - 操作数据库的正确方法