2011-04-06 57 views
0

我一直在記錄控制面板用戶的窗口高度。MySQL查詢獲取列的模態平均值?

我有一個表像這樣:

user_id(INT) | window_height(INT) 
-------------------------------- 
123   | 1200 
124   | 1200 
125   | 1100 
126   | 1200 

我有幾千行,並希望得到模態的平均值。

即1200像素= 300users,1100px = 125users,500像素= 12users

我正在尋找一個MySQL查詢我可以只撞到phpMyAdmin的....

回答

1

要獲得原料計數

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的技巧,使用變量來存儲最大計數,因爲它通過聚合子查詢。操作

  • O(N)摘要:掃描表一次,並建立計數(T1)
  • O(N):掃描派生表T1,並保持在變量@r最高計數(T2)
  • 爲O(n):掃描派生表T2和僅具有最高計數
篩選的高度