简体   繁体   中英

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.

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). 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?

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

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