简体   繁体   中英

How to pull top 3 per group in access SQL

I'm attempting to pull the top three performers in a group. I'm not sure how to do this in Access, what I need is for each group to pull the top three.

http://allenbrowne.com/subquery-01.html

I've tried these subqueries however they give me an error message. Is there a better way to do this?

It's for keyword performance.

Table fields are

Keyword | Campaign | Ad Group |  Clicks | Impressions 

I want the top 3 for clicks for each ad group. I want top 3 impressions too but once I know how to do clicks I'll be able to modify it as needed. I'm trying to get like

Ad Group 1 - First Top
Ad Group 1 - Second Top
Ad Group 1 - Third Top
Ad Group 2 - First Top
Ad Group 2 - Second Top
Ad Group 2 - Third Top
etc

SELECT KeywordReport.ID, KeywordReport.Campaign, KeywordReport.[Ad group], KeywordReport.Keyword, KeywordReport.Clicks, KeywordReport.Impressions, KeywordReport.[Avg CPC], KeywordReport.[Search Impr share], KeywordReport.Cost
FROM KeywordReport
WHERE (((KeywordReport.ID) In (SELECT TOP 3 ID 
FROM KeywordReport AS Dupe
WHERE Dupe.ID = KeywordReport.ID
ORDER BY Dupe.Clicks DESC)))
ORDER BY KeywordReport.[Ad group];

It is returning all entries not the top 3.

I think you were close:

WHERE (((KeywordReport.ID) In (SELECT TOP 3 ID 
FROM KeywordReport AS Dupe
WHERE Dupe.[Ad Group] = KeywordReport.[Ad Group]   <-- change this line
ORDER BY Dupe.Clicks DESC)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM