可以計算與GROUP BY在MySQL中位數即使是沒有內置位機能
考慮表:
Acrington 200.00
Acrington 200.00
Acrington 300.00
Acrington 400.00
Bulingdon 200.00
Bulingdon 300.00
Bulingdon 400.00
Bulingdon 500.00
Cardington 100.00
Cardington 149.00
Cardington 151.00
Cardington 300.00
Cardington 300.00
對於每一行,你可以計算較少的類似項目的數量。您也可以算多少值都小於或等於:
name v < <=
Acrington 200.00 0 2
Acrington 200.00 0 2
Acrington 300.00 2 3
Acrington 400.00 3 4
Bulingdon 200.00 0 1
Bulingdon 300.00 1 2
Bulingdon 400.00 2 3
Bulingdon 500.00 3 4
Cardington 100.00 0 1
Cardington 149.00 1 2
Cardington 151.00 2 3
Cardington 300.00 3 5
Cardington 300.00 3 5
通過查詢會發生
SELECT name,v, (SELECT COUNT(1) FROM sale WHERE v<o.v AND name=o.name) as ls
, (SELECT COUNT(1) FROM sale WHERE v<=o.v AND name=o.name) as lse
FROM sale o
中值當低於或相等計數的項目數的一半
Acrington有4個項目。的這一半是2這是在(對應於200.00)的範圍0..2以及在(對應於300.00)的範圍2..3
Bullingdon也有4個項目。 2在範圍1..2(值300.00)和2..3(值400.00)
Cardington有5項。值2.5在2和3之間,對應於Cardington 151。
中值是最小的平均值和最大值由歸國:
SELECT cs.name,v
FROM
(SELECT name,v, (SELECT COUNT(1) FROM sale WHERE v<o.v AND name=o.name) as ls
, (SELECT COUNT(1) FROM sale WHERE v<=o.v AND name=o.name) as lse
FROM sale o) cs JOIN
(SELECT name,COUNT(1)*.5 as cn
FROM sale
GROUP BY name) cc ON cs.name=cc.name
WHERE cn between ls and lse
其中給出:
Acrington 200.00
Acrington 200.00
Acrington 300.00
Bulingdon 300.00
Bulingdon 400.00
Cardington 151.00
最後,我們可以得到位數:
SELECT name,(MAX(v)+MIN(v))/2 FROM
(SELECT cs.name,v
FROM
(SELECT name,v, (SELECT COUNT(1) FROM sale WHERE v<o.v AND name=o.name) as ls
, (SELECT COUNT(1) FROM sale WHERE v<=o.v AND name=o.name) as lse
FROM sale o) cs JOIN
(SELECT name,COUNT(1)*.5 as cn
FROM sale
GROUP BY name) cc ON cs.name=cc.name
WHERE cn between ls and lse
) AS medians
GROUP BY name
給予
Acrington 250.000000
Bulingdon 350.000000
Cardington 151.000000
mysql中沒有中位數函數 – 2013-10-29 09:33:21
是否必須處於同一個查詢中?如果可以運行第二個查詢,則可以計算該集合的中點,以知道數據點的數量。中點是一行或兩行。運行相同的查詢,但添加LIMIT [中點],[中點mod 2]並返回平均值。 – 2013-10-30 06:50:56
如果你這樣做,你將不得不改變順序 - 我假設你想要QNTY_Sell/QNTYDelivered的中位數,所以你必須命令它來找到中點。 – nickL 2014-01-22 18:50:06