简体   繁体   中英

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
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() :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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