+ Start a Discussion
ScottB3ScottB3 

SOQL Retrieve most recent CampaignMember for a set of leads

I have a set of leads for which I need to find the most recent campaign that they are a member of.

Since there may be more than 100 leads in the set, I am trying to write a single SOQL query that will return only the CampaignMember Id with the most recent CreatedDate for each lead, rather than put a query inside of a for-loop

I need something along the lines of this, but with the actual ID of the CampaignMember object instead of the count.
 
SELECT count(Id), LeadID, max(CreatedDate) FROM CampaignMember WHERE LeadID IN :setOfLeads GROUP BY LeadID

 
Best Answer chosen by ScottB3
ScottB3ScottB3

In case someone else is wondering how.

 

SELECT Id, Name, (SELECT ID, CreatedDate From CampaignMembers ORDER BY CreatedDate DESC LIMIT 1) FROM Lead WHERE Id IN :leadList