来自:
http://mdb-blog.blogspot.com/2015/06/mysql-find-median-nth-element-without.html
我建议另一种方法,不用连接,
但是处理字符串
我没有用大数据表来检验,
但是中小型的桌子就可以了。
这里的好处是,它也可以通过GROUPING工作,所以它可以返回几个项目的中值。
下面是测试表的测试代码:
DROP TABLE test.test_median
CREATE TABLE test.test_median AS
SELECT 'book' AS grp, 4 AS val UNION ALL
SELECT 'book', 7 UNION ALL
SELECT 'book', 2 UNION ALL
SELECT 'book', 2 UNION ALL
SELECT 'book', 9 UNION ALL
SELECT 'book', 8 UNION ALL
SELECT 'book', 3 UNION ALL
SELECT 'note', 11 UNION ALL
SELECT 'bike', 22 UNION ALL
SELECT 'bike', 26
求每组中位数的代码:
SELECT grp,
SUBSTRING_INDEX( SUBSTRING_INDEX( GROUP_CONCAT(val ORDER BY val), ',', COUNT(*)/2 ), ',', -1) as the_median,
GROUP_CONCAT(val ORDER BY val) as all_vals_for_debug
FROM test.test_median
GROUP BY grp
输出:
grp | the_median| all_vals_for_debug
bike| 22 | 22,26
book| 4 | 2,2,3,4,7,8,9
note| 11 | 11