[英]MySQL query to get the modal averages of a column?
I've been recording the window height of users of my control panel. 我一直在记录控制面板用户的窗口高度。
I have a table like so: 我有这样的一张桌子:
user_id(INT) | window_height(INT)
--------------------------------
123 | 1200
124 | 1200
125 | 1100
126 | 1200
I have thousands of rows and would like to get the Modal averages. 我有成千上万的行,并希望获得模态平均值。
ie 1200px = 300users, 1100px = 125users, 500px = 12users 即1200px = 300users,1100px = 125users,500px = 12users
I'm looking for a MySQL query i can just bang into PhpMyAdmin.... 我正在寻找一个MySQL查询,我可以直接进入PhpMyAdmin。
To get raw counts 获取原始计数
select window_height, count(*) totalusers
from tbl
group by window_height
order by totalusers desc # or by window_height
To get the modal average (this will show multiple values if there are ties for the highest count) 获取模态平均值(如果存在最高计数,则将显示多个值)
select window_height, totalusers
from (
select @r := if(totalusers>@r,totalusers,@r) maxcount, window_height, totalusers
from (select @r:=0) initvars, (
select window_height, count(*) totalusers
from tbl
group by window_height
) X ) Y
where totalusers = @r
This uses a MySQL trick of using a variable to store the max count as it goes through the aggregated subquery. 这使用了MySQL的技巧,即使用变量来存储通过聚合子查询时的最大计数。 Summary of operations 运营摘要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.