Question : Select Top 5 For Each Group - subquery syntax bug

Hi all - painfully stumped for a Friday.  Trying to implement any of these three previous solutions to 'selecting top x for each group' type problem: Select top members with most claims total for each group (Last_Name).

Member_ID   Last_Name   Total
001              Palmetto         12
002              Trident            10
003              Palmetto          9
004              Macy               4
005              Macy               1
006              Macy               9

Result (for Top 1):
001          Palmetto    12
002          Trident       10
006          Macy          9

Templates:
http://www.experts-exchange.com/Databases/MS_Access/Q_21464877.html
http://www.experts-exchange.com/Databases/MS_Access/Q_20729610.html
http://www.experts-exchange.com/Databases/MS_Access/Q_10699721.html (paasky's 12:30 comment)

all of which use basic subquery structure which i copied to use below like:

SELECT MEMBER_ID, LAST_NAME, TOTAL
FROM q_RxSav_7s2_MembersClaimsActivity AS Q1
WHERE  TOTAL IN
   (SELECT TOP 2 Q2.TOTAL
FROM q_RxSav_7s2_MembersClaimsActivity AS Q2
WHERE Q1.LAST_NAME = Q2.LAST_NAME
ORDER BY Q2.CLAIMS DESC)

and which is causing me endless grief in Access2000 - either undefined syntax err, does not recognize 'Q1.LAST_NAME' as valid, or missing 'EXSISTS' instead of where in - none of which i can get to work.

any ideas??

thanks, wes



Answer : Select Top 5 For Each Group - subquery syntax bug

Hello new_wes

Given your sample data, you must use Member_ID as link field, not Totals. On the other hand, I find it very strange that you have several different Member_ID's for the same name...

Anyway:

SELECT MEMBER_ID, LAST_NAME, TOTAL
FROM q_RxSav_7s2_MembersClaimsActivity AS Q1
WHERE  MEMBER_ID IN
   (SELECT TOP 2 MemberID
   FROM q_RxSav_7s2_MembersClaimsActivity AS Q2
   WHERE LAST_NAME = Q1.LAST_NAME
   ORDER BY TOTAL DESC)

If that doesn't work, it's probably because you have a query that is not compatible as a subquery. Try to rewrite this based on the tables, not q_RxSav_7s2_MembersClaimsActivity. Or it will be impossible to debug.

(°v°)
Random Solutions  
 
programming4us programming4us