MySQL工作台最大计数

时间:2017-09-12 11:23:43

标签: mysql count max

作为一个SQL goofball,我完全陷入困境,试图最多进行2列计数。

我有一个交易数据库,我希望为每个用户获得最高频率的收件人。

数据是:

User  Recipient 
 A        B
 A        C
 A        B
 A        F
 D        A
 D        C
 D        A
 D        A

期望的结果是

User Recipient Count
 A      B       2
 D      A       3

我设法得到了计数,但我似乎无法获得最大收件人。

我尝试过使用内部联接和where语句,但它无法正常工作。

如果是关系,则显示哪个值无关紧要。

1 个答案:

答案 0 :(得分:2)

在MySQL中获得最大值有点痛苦。这是一种方法:

select user, recipient, count(*)
from t
group by user, recipient
having count(*) = (select count(*)
                   from t t2
                   where t2.user = t.user
                   group by user, recipient
                   order by count(*) desc
                   limit 1
                  );

注意:当存在关联时,此版本将返回重复项。如果您不想复制,可以改为:

select user, recipient, count(*)
from t
group by user, recipient
having recipient = (select recipient
                    from t t2
                    where t2.user = t.user
                    group by user, recipient
                    order by count(*) desc
                    limit 1
                   );