简体   繁体   English

如何获得按 MySQL 中的字段分组的最大计数?

[英]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 )?如何按商店获得销量最高的电影(= 按film_id分组的表中经常出现的电影store_id )? My guess is that would be the max() count(movie_id) but I can't figure out how to make this work.我的猜测是max() count(movie_id)但我不知道如何使这项工作。

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:如果您的 MySql 版本是 8.0+,您可以使用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.如果 2 部电影在商店中均等地售出,这将返回平局。
See the demo .演示
For previous versions of MySql you could do this:对于以前版本的 MySql 你可以这样做:

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     |

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

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