2013-03-11 76 views
1

我正在计算价格的中位数。 我创建了答案如何在这里做到这一点,Simple way to calculate median with MySQL,但它不适合我,我得到空的结果。 任何人都可以帮忙吗?MySQL:计数中位数值

SELECT x.price from mediana as x, mediana y 
GROUP BY x.price 
HAVING SUM(SIGN(1-SIGN(y.price-x.price))) = (COUNT(*)+1)/2 
+0

你能证明这一点与sqlfiddle? – 2013-03-11 12:32:49

+0

您是否尝试过大多数投票(未被接受)的答案? [执行示例](http://sqlfiddle.com/#!2/fbd31/6) – 2013-03-11 12:40:57

+0

http://sqlfiddle.com/#!2/b3fe7e/1 – Alex 2013-03-11 12:44:22

回答

2

AFAIU你的问题。

This answer by @velcrow成功地计算了中值。不幸的是,当有偶数行而不是计算2个中间行的查询的平均值时,只返回第二个值。我做了一对夫妇对查询的修改,以适应您的需求:

--average value for middle rows 
SELECT avg(t1.price) as median_val FROM (
SELECT @rownum:[email protected]+1 as `row_number`, d.price 
    FROM mediana d, (SELECT @rownum:=0) r 
    WHERE 1 
    -- put some where clause here 
    ORDER BY d.price 
) as t1, 
(
    SELECT count(*) as total_rows 
    FROM mediana d 
    WHERE 1 
    -- put same where clause here 
) as t2 
WHERE 1 
--this condition should return one record for odd number of rows and 2 middle records for even. 
AND t1.row_number>=total_rows/2 and t1.row_number<=total_rows/2+1; 

Test on sample data on sqlfiddle

+0

这将返回错误的结果,它返回2 – 2013-03-11 13:35:00

+0

对于价格1,2,3,4它返回 - 2.5,对于1,2,3,4,4返回3,所以它是正确的;) – Alex 2013-03-11 13:40:59