简体   繁体   English

MySQL通过Group By选择最大出现次数

[英]MySQL Select Max Occurrence with Group By

I have a table (log_entries): 我有一张桌子(log_entries):

id|token|area|
 1| 543 | AA |
 2| 452 | BB |
 3| 543 | BB |
 4| 634 | CC |
 5| 436 | AA |

I want to create a list of the top 5 areas, grouped by token, however the area used is the last area that token used. 我想创建按令牌分组的前5个区域的列表,但是使用的区域是令牌使用的最后一个区域。 Basically a list of the top 5 areas where each token only gets one vote and it's vote is for the last area it was logged with. 基本上,前5个区域的列表中,每个令牌仅获得一票,而投票是记录其的最后一个区域。

For example, for the table above, the list would look like: 例如,对于上表,列表如下所示:

|area|count|
| BB |  2  |
| AA |  1  |
| CC |  1  |

How do I do this in a MySQL statement? 如何在MySQL语句中执行此操作? (BTW the table is large > 50,000 rows) (顺便说一句,表很大> 50,000行)

SQL tables represent unordered sets. SQL表表示无序集。 You need another column to specify the ordering. 您需要另一列来指定顺序。

Here is one way to get the most recent area for each token: 这是获取每个令牌的最新区域的一种方法:

select area, count(*)
from (select t.*,
             (@rn := if(@t = token, @rn + 1,
                        if(@t := token, 1, 1)
                       )
             ) as seqnum
      from t cross join
           (select @rn := 0, @t := '') params
      order by tokens, ??
     ) t
where seqnum = 1
group by area
order by count(*) desc;

You need to replace the ?? 您需要更换?? with the column name that specifies the ordering to determine the most recent. 列名称用于指定确定最新顺序的顺序。

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

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