MySQL:选择按值的频率排序的行

时间:2010-11-19 11:49:24

标签: mysql

假设下表:

People
---------------------------
id | First Name | Last Name

我如何选择最常用的名字ORDERed的行?

3 个答案:

答案 0 :(得分:2)

select 
  count(firstname) as countFn, 
  firstname 
from people 
group by firstname 
order by countFn desc

修改:从选择

中删除了ID和姓氏

答案 1 :(得分:1)

select p.*, t.count
from people p
, (select FirstName, count(1) as count
   from people
   group by FirstName) t
where p.FirstName = t.FirstName
order by t.count desc;

答案 2 :(得分:0)

如果您需要按降序查看按名字数排序的所有名称,那么对于Oracle,这将起作用:

select n.firstname, n.lastname, g.count 
from 
people n, (select firstname, count(*) count from people group by firstname) g
where n.firstname=g.firstname
order by g.count desc

不确定这是如何工作的,例如MySQL的。