作为一个 SQL 傻瓜,我对尝试最多 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 语句,但都失败了。
在平局的情况下,显示哪个值并不重要。
最佳答案
在 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
);
关于MySQL Workbench 最大计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46175149/