[英]MySQL query to get the modal averages of a column?
我一直在记录控制面板用户的窗口高度。
我有这样的一张桌子:
user_id(INT) | window_height(INT)
--------------------------------
123 | 1200
124 | 1200
125 | 1100
126 | 1200
我有成千上万的行,并希望获得模态平均值。
即1200px = 300users,1100px = 125users,500px = 12users
我正在寻找一个MySQL查询,我可以直接进入PhpMyAdmin。
获取原始计数
select window_height, count(*) totalusers
from tbl
group by window_height
order by totalusers desc # or by window_height
获取模态平均值(如果存在最高计数,则将显示多个值)
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
这使用了MySQL的技巧,即使用变量来存储通过聚合子查询时的最大计数。 运营摘要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.