简体   繁体   English

mysql 获取具有最大聚合计数的条目

[英]mysql get entry with max count of aggregation

I have an email_patterns table and I would like to find the most common pattern for each domain:我有一个 email_patterns 表,我想为每个域找到最常见的模式:

email_patterns
id, domain, pattern
1, microsoft.com, first.last
2, microsoft.com, first.last
3, microsoft.com, last.first
4, microsoft.com, first
5, apple.com, last
6, apple.com, last.first
7, apple.com, last.first

The query should return查询应该返回

domain, pattern, count
microsoft.com, first.last, 2
apple.com, last.first, 2

This is how to get the counts for each domain, pattern combination:这是获取每个域、模式组合的计数的方法:

SELECT domain, pattern, COUNT(1) count FROM email_patterns GROUP BY domain, pattern;

However, I only want to get the domain pattern combination with the highest count for each domain.但是,我只想获得每个域的计数最高的域模式组合。

Next you just need ROW_NUMBER() :接下来你只需要ROW_NUMBER()

SELECT domain, pattern, cnt
FROM (SELECT domain, pattern, COUNT(*) as cnt,
             ROW_NUMBER() OVER (PARTITION BY domain ORDER BY COUNT(*) DESC) as seqnum
      FROM email_patterns
      GROUP BY domain, pattern
     ) dp
WHERE seqnum = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM