Determining Mode in a Query

S

Steven Reames

I'd like to determine the mode (most common result) of [DonationAmount] for
each individual household record [nhouseholdID] in Table_Donations.
 
D

Dale Fye

Steven,

The problem with the mode is that it can return multiple values (bi-modal),
so what do you want to return if there are mutiple values which are "most
common" for a particular household? I have a function on my home computer
(not there right now) that I use for this (assumes a single mode). It looks
something like (untested):

Public Function fnMode(FieldName as String,
PKFieldName as String, _
Source as String, _
Optional Criteria as Variant = Null) as
Variant

'Returns a variant because the 'FieldName' field could be any data type.

Dim strSQL as string
Dim rs as DAO.Recordset
Dim lngFreq as Long

strSQL = "SELECT [" & FieldName & "], " _
& "COUNT([" & PKFieldName & "]) as Freq " _
& "FROM [" & TableName & "] " _
& ("WHERE " + Criteria) _
& " GROUP BY [" & FieldName & "] " _
& " ORDER BY COUNT([" & PKFieldName & "]) DESC"
strSQL = Replace(strSQL, "[[", "[")
strSQL = Replace(strSQL, "]]", "]")
Set rs = Currentdb.Openrecordset(strsql,,dbfailonerror)

if rs.eof then
fnMode = NULL
else
fnMode = rs(0)
endif

rs.close
set rs = nothing

End Function

Then, to use this in a query, you would do something like the following
(assumes you have a PK field named ID):

SELECT T.[nhouseholdID], fnMode("[DonationAmount]", "ID", "yourTable",
"[nHouseholdID] = " & t.nhouseholdID) as Mode
FROM yourTable
GROUP BY T.nHouseHoldID
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top