Discussion Locked

How to select top records in Access

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have a table with two fields, State and Amount. There are multiple records for each state. I would like to select the top 2 records for each state. For example, my data looks like this:
NC $45
NC $50
NC $55
VA $20
VA $30
VA $25
PA$10
PA $5
PA $20
PA $30

I would like to have a query that would extract the following records from the data above
NC $55
NC $50
VA $30
VA $25
PA $30
PA $20

How would I go about doing this. Thanks.

3 replies

by r. a. caluste

i am not sure if you can do a custom filter such as the one you wanted but if i were to do that query, i would write a module such as:

public sub CustomQuery()
dim dbspace as database
dim topstate, secstate as string
dim topstatedata, secstatedata as currency
Dim rs As Recordset
Dim rs2 As Recordset

set dbspace = currentdb

on error resume next
'if table is missing, ignore
dbspace.execute "DROP Table qryTopTwo"
on error goto 0

dbspace.execute ("CREATE Table qryTopTwo ([State] TEXT, [Statedata] Currency)")

Set rs = CurrentDb.OpenRecordset("SELECT DISTINCT state from MyTable")
Do Until rs.EOF
Set rs2 = CurrentDb.OpenRecordset("SELECT * from MyTable where state = '" & rs!state & "'")
'get top two datatopstate = rs2!state
topstatedata = rs2!statedata
rs2.movenext
secstate = rs2!state
secstatedata = rs2!statedata
rs2.movenext
'loop and see if any record tops the first two
Do Until rs2.EOF
if rs2!statedata > topstatedata then
secstate = topstate
secstatedata = topstatedata
topstate = rs2!state
topstatedata = rs2!statedata
end if
if rs2!statedata > secstatedata then
secstate = rs2!state
secstatedata = rs2!statedata
end if
rs2.MoveNext
Loop
'write top two data into qryTopTwo table
dbspace.execute "INSERT INTO qryTopTwo (State, Statedata) values ('" & topstate & "', " & topstatedata & ")"
dbspace.execute "INSERT INTO qryTopTwo (State, Statedata) values ('" & secstate & "', " & secstatedata & ")"
rs2.Close
rs.MoveNext
Loop
rs.Close
End Sub

the above module will create a table named qryTopTwo with result similar to your requirement.

by siggih

Another way to do this is to use Access specific SQL command top.
the TOP command gives you .. top X results.

used like this 'select TOP 2 amount, state ....'

See Access help for details ... search for TOP or TopValues.

by gcheels

When I copied this procedure into my database I received a "User-defined type - not defined" on the line: DIM DBSPACE = DATABASE. I changed the argument to an Object type, but got an error further down in the code. A Type-mismatch on the "SET RS" line. What am I doing wrong. Thanks.

This discussion is closed to new replies.