MySQL query to get the modal averages of a column?

后端 未结 1 593
时光说笑
时光说笑 2021-01-28 10:39

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)
--------------------------         


        
1条回答
  •  清歌不尽
    2021-01-28 11:09

    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. Summary of operations

    • O(n): scan table once and build the counts (T1)
    • O(n): scan the derived table T1 and keep the highest count in the variable @r (T2)
    • O(n): scan the derived table T2 and filter only for the heights with the highest count

    0 讨论(0)
提交回复
热议问题