• Matt Quinlan
  • NEWBIE
  • 5 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

I'd like to get the dates of the most recently completed activities for each of a set of contacts by using a single SOQL query.

I realize that I could fetch all completed activities for those contacts and iterate through them to find the most recent ones, but I'm wondering if it's possible to do this in a single query that only returns the data I need.

If I were writing SQL instead of SOQL, I would do something like the examples below. (I've omitted the where clauses for simplicity.)

select WhoId, Max(ActivityDate) 
from Task where ... Group By WhoId

 or less optimally,

select WhoId, 
   (select top 1 from ActivityDate from Task T2 where T1.Id = T2.Id order by ActivityDate desc)
from Task T1
where ...
Group By WhoId

 

Neither of these approaches seems to translate directly to SOQL. Is there an alternative?