用MySQL计算中值的简单方法用MySQL计算中位数最简单的方法(希望不是太慢)是什么?我用过AVG(x)但是我很难找到一种简单的计算中值的方法。现在,我将所有行返回到PHP,进行排序,然后选择中间行,但肯定有一些简单的方法可以在一个MySQL查询中完成。示例数据:id | val--------
1 4
2 7
3 2
4 2
5 9
6 8
7 3分拣val施予2 2 3 4 7 8 9,所以中值应该是4、对决SELECT AVG(val)其中=5.
3 回答
aluckdog
TA贡献1847条经验 获得超7个赞
SELECT AVG(dd.val) as median_valFROM (SELECT d.val, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum FROM data d, (SELECT @rownum:=0) r WHERE d.val is NOT NULL -- put some where clause here ORDER BY d.val) as ddWHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows+2)/2) );
AVG(dd.val)
dd.row_number IN(...)
SELECT FLOOR((3+1)/2),FLOOR((3+2)/2); -- when total_rows is 3, avg rows 2 and 2SELECT FLOOR((4+1)/2),FLOOR((4+2)/2); -- when total_rows is 4, avg rows 2 and 3
GCT1015
TA贡献1827条经验 获得超4个赞
对于几乎所有SQL中的中介: SELECT x.val from data x, data yGROUP BY x.valHAVING SUM(SIGN(1-SIGN(y.val-x.val))) = (COUNT(*)+1)/2
select count(*) from table --find the number of rows
median_row = floor(count / 2)
.
select val from table order by val asc limit median_row,1
慕运维8079593
TA贡献1876条经验 获得超5个赞
SELECT x.val from data x, data yGROUP BY x.valHAVING SUM(SIGN(1-SIGN(y.val-x.val)))/COUNT(*) > .5LIMIT 1
添加回答
举报
0/150
提交
取消