我正在計算價格的中位數。 我創建了答案如何在這裏做到這一點,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
我正在計算價格的中位數。 我創建了答案如何在這裏做到這一點,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
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;
這將返回錯誤的結果,它返回2 – 2013-03-11 13:35:00
對於價格1,2,3,4它返回 - 2.5,對於1,2,3,4,4返回3,所以它是正確的;) – Alex 2013-03-11 13:40:59
你能證明這一點與sqlfiddle? – 2013-03-11 12:32:49
您是否嘗試過大多數投票(未被接受)的答案? [執行示例](http://sqlfiddle.com/#!2/fbd31/6) – 2013-03-11 12:40:57
http://sqlfiddle.com/#!2/b3fe7e/1 – Alex 2013-03-11 12:44:22