选择多个最大行

时间:2012-09-22 12:23:38

标签: mysql sql

假设我有一个名为Domain的MySQL表。如何从此表中找到最受欢迎的电子邮件域。我想直接找到所有具有最大计数的行。

Domain    
gmail.com    
gmail.com    
gmail.com    
yahoo.com    
yahoo.com    
yahoo.com    
rediffmail.com    
rediffmail.com
mail.com

我想要的输出:

Domain      No_of_users
gmail.com   3
yahoo.com   3

2 个答案:

答案 0 :(得分:2)

select
  x.Domain,
  x.No_of_users
from
  (select
    d.Domain, 
    count(d.Domain) as No_of_users
  from
    Domain d
  group by 
    d.Domain) x
where
  x.No_of_users = 
    (select
      max(x2.No_of_users)
    from
      (select
         d2.Domain,
         count(d2.Domain) as No_of_users
      from
         Domain d2
      group by 
        d2.Domain) x2)

答案 1 :(得分:2)

SELECT Domain, count(id)
FROM Domain
GROUP BY Domain.Domain
HAVING count(id) = (SELECT count(id) FROM Domain D GROUP BY D.Domain ORDER BY count(id) DESC LIMIT 1)