Simple way to calculate median with MySQL

后端 未结 30 1571
北荒
北荒 2020-11-22 04:20

What\'s the simplest (and hopefully not too slow) way to calculate the median with MySQL? I\'ve used AVG(x) for finding the mean, but I\'m having a hard time fi

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 04:47

    My solution presented below works in just one query without creation of table, variable or even sub-query. Plus, it allows you to get median for each group in group-by queries (this is what i needed !):

    SELECT `columnA`, 
    SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(`columnB` ORDER BY `columnB`), ',', CEILING((COUNT(`columnB`)/2))), ',', -1) medianOfColumnB
    FROM `tableC`
    -- some where clause if you want
    GROUP BY `columnA`;
    

    It works because of a smart use of group_concat and substring_index.

    But, to allow big group_concat, you have to set group_concat_max_len to a higher value (1024 char by default). You can set it like that (for current sql session) :

    SET SESSION group_concat_max_len = 10000; 
    -- up to 4294967295 in 32-bits platform.
    

    More infos for group_concat_max_len: https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_group_concat_max_len

提交回复
热议问题