简体   繁体   English

按mysql中字段的最高记录数排序

[英]Order by highest number of records in a field in mysql

I'd like to order contents of a table from MySQL database that looks like below. 我想从如下所示的MySQL数据库订购表的内容。

name,h1,h2
a,f1,3
a,g3,5
a,h3,4
b,g3,4
c,h5,2
c,j12,6

I'd like to get the lengths for each element in name column ie, length of 'a' would be 3 (since it has three rows of data associated with it) and get data of the top 2 elements (here it'd include 3 rows for a's and 2 for c's since they have the highest length in descending order). 我想获取名称列中每个元素的长度,即“ a”的长度为3(因为它与三行数据相关联),并获取前2个元素的数据 (此处包括a的3行和c的2行,因为它们具有最大长度的降序排列。 So the required output would look something like below 因此所需的输出如下所示

name,h1,h2
a,f1,3
a,g3,5
a,h3,4
c,h5,2
c,j12,6

How can this be achieved in MySQL? 如何在MySQL中实现?

Joining to a count of the top two records should give you your results. 加入前两个记录的计数将为您提供结果。

select
  t.*
from
  table1 t
  inner join (select 
                name, 
                count(*) as cnt 
              from table1 
              group by name
              order by count(*) desc
              limit 2) as c on t.name = c.name
order by c.cnt desc

Here's a fiddle 这是一个小提琴

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

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