I wish to get the top 5 opportunities for each user.
I do:
SELECT OwnerId, Amount, Probability, ExpectedRevenue
FROM Opportunity
WHERE isClosed = False
AND Opportunity.OwnerID IN :userIDs
AND ExpectedRevenue > 0 ORDER BY OwnerId, ExpectedRevenue DESC
I iterate over result set and pick out top 5 for each user. Easy. However, the problem is say you have 50 users with 1,001 opps each. You are going to hit the 50,000 governor limit.
I need to restructure this query so that it only returns the top 5 for each user which means it will only return 50 * 5 = 250 records.
I know about the limit keyword but I can't limit this query to 250 because that could just get me 250 opps from the 1st user who has 1,000 opps.
Any tips?

SELECT Id, (SELECT Id FROM Opportunities ORDER BY ExpectedRevenue DESC LIMIT 5) FROM Userbut the User object is special. Relationship between Opportunity and the Owner is not named (comes blank as result of the describe), it's not "Opportunities", not "OwnedOpportunities"... – eyescream Jan 30 at 16:22Owner__cfield, perform initial data load and later keep it in sync with workflow. You should have no problems using it in the query... Sounds a bit hacky though. Or write a trigger that makes the owner an auto member of OpportunityTeam (Role = 'Owner'?), relationship name for that isOpportunityTeams. – eyescream Jan 30 at 17:04