function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ 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