VBA中位數函式

2021-09-26 15:32:10 字數 2497 閱讀 7247

最近在做財務分析方面的開發,遇到了中位數據的問題,中位數在excel中使用非常的方便,有現成的函式【median】,直接拿來用就可以了,但在access中該怎麼操作呢?

中位數(median)又稱中值,統計學中的專有名詞,是按順序排列的一組資料中居於中間位置的數,代表乙個樣本、種群或概率分布中的乙個數值,其可將數值集合劃分為相等的上下兩部分。對於有限的數集,可以通過把所有觀察值高低排序後找出正中間的乙個作為中位數。如果觀察值有偶數個,通常取最中間的兩個數值的平均數作為中位數。

定義:中位數,又稱中點數,中值。中位數是按順序排列的一組資料中居於中間位置的數,即在這組資料中,有一半的資料比他大,有一半的資料比他小,這裡用 來表示中位數。(注意:中位數和眾數不同,眾數指最多的數,眾數有時不止乙個,而中位數只能有乙個。)

了解什麼是中位數,然後結合公式,我們就動手開發中位數了。我們以工資中位數做為今天的示例。那麼有人就問了,為什麼工資不取平均數呢?你想想,如果你和馬雲爸爸取一下平均資料,那是不是就不沒參考意思了,這個時候我們就要用中位數了。

中位數據函式,已經給大家寫好了,將下面的**新增到通用模組

public function mediannumber(byval strfile as string, byref strtable as string, optional strwhere as string = "") as single

on error goto errorhandler

dim strsql as string

dim rst as object

dim gcount as long

dim strdata as string

dim vardata as variant

dim varid as variant

dim cnn as object

strsql = "select @strfile from @strtable @where order by @strfile"

strsql = replace(strsql, "@strfile", strfile)

strsql = replace(strsql, "@strtable", strtable)

if strwhere <> "" then

strsql = replace(strsql, "@where", " where " & strwhere)

else

strsql = replace(strsql, "@where", "")

end if

' debug.print strsql

set rst = createobject("adodb.recordset")

set cnn = currentproject.connection

rst.open strsql, cnn, adopenkeyset, adlockoptimistic

' set rst = currentdb.openrecordset(strsql)

if rst.recordcount > 0 then

gcount = rst.recordcount

rst.movefirst

else

mediannumber = 0

goto exithere

end if

strdata = ""

do until rst.eof

strdata = strdata & rst.fields(0) & ";"

rst.movenext

loop

rst.close

' debug.print strdata

vardata = split(strdata, ";")

if gcount mod 2 <> 0 then '判斷奇偶數

mediannumber = vardata((ubound(vardata) + 1) / 2 - 1) '如果是奇資料,中位數=x(n+1)/2,要注意下標,因為資料的下標是從0開始

else

'如果是偶數,中位數=(x(n/2)+x(n/2+1))/2

mediannumber = (val(vardata(ubound(vardata) / 2 - 1)) + val(vardata(ubound(vardata) / 2))) / 2

end if

exithere:

set cnn = nothing

set rst = nothing

exit function

errorhandler:

msgboxex err.description, vbcritical

resume exithere

end function

最後,要和大家講的是,有些函式在excel都是有現成的,但在access中可能就需要自己來定義了,所以大家不要想當然的就在access中使用,然後還問為什麼在excel可以,access不能用這類的問題。

提取碼:itxk

中位數的中位數

參照王曉東的演算法設計 中位數的中位數,即將一串數分成n段,求其排好序了的中間那個數,再把這些所有中位數再求一次中位數。for int i 0 i r p 4 5 i 找中位數的中位數,r p 4即上面所說的n 5 int x lineselect a,p,p r p 4 5,r p 4 10 線性...

BFPRT(中位數的中位數)演算法

又稱為 中位數的中位數演算法 該演算法由 blum floyd pratt rivest tarjan 在1973年提出,最壞時間複雜度為o n 最差的空間複雜度為o logn 演算法步驟 1 將 n 個元素劃分為 n 5 個組,每組 5 個元素,若有剩餘,捨去 2 使用排序方法找到 n 5 個組中...

hive 中位數 Hive的中位數

關於求解中位數,我們知道在python中直接有中位數處理函式 mean 比如在python中求解乙個中位數,很簡單。python計算中位數 import numpy as np nums 1.1,2.2,3.3,4.4,5.5,6.6 均值np.mean nums 中位數 np.median num...