简体   繁体   中英

How to get the max count grouped by a field in MySQL?

Given this table which contains the list of the movies sold by a store:

store_id | film_id
---------|--------
1        | 123
1        | 32
2        | 145
1        | 123
2        | 84
2        | 456
1        | 6
2        | 456

How can I get the most sold movie by store ( = the most reccurent film_id in the table grouped by store_id )? My guess is that would be the max() count(movie_id) but I can't figure out how to make this work.

I'm trying to get this kind of result:

store_id | mostSoldMovieId
---------|--------
1        | 123
2        | 456

If your version of MySql is 8.0+ you can use RANK() window function:

select t.store_id, t.film_id mostSoldMovieId
from (
  select store_id, film_id,
    rank() over (partition by store_id order by count(*) desc) rn
  from tablename
  group by store_id, film_id
) t
where t.rn = 1

This will return ties if 2 films are at the top equally sold for a store.
See the demo .
For previous versions of MySql you could do this:

select 
  t.store_id,
  substring_index(group_concat(t.film_id order by counter desc), ',', 1) film_id
from (
  select store_id, film_id, count(*) counter
  from tablename
  group by store_id, film_id
) t  
group by t.store_id

This will not return ties.
See the demo .
Results:

| store_id | film_id |
| -------- | ------- |
| 1        | 123     |
| 2        | 456     |

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