You need to sign in to do that
Don't have an account?

SOQL query for the most recent ActivityDates for each contact in a set
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?
You can use "order by" clause in the query and use the first result to get the most recent completed activity
Thanks raseshtcs. I'm trying to get the most recent activity date for each contact. My original post might have been misunderstood on that point; I've updated it to clarify.
ActivityDate can't be ordered by without being grouped or aggregated.
Grouping by both WhoId and ActivityDate will return the dates for all activities, which is what I'm trying to avoid. A "limit x" clause won't help because that would just give me the x most recent activities, not the most recent activity for each contact.
I'd love to aggregate it (i.e., call "MAX(ActivityDate)"), but it doesn't seem to be supported. The API documentation here indicates that MAX() supports date types, however when I try to save the Apex I get the error "field ActivityDate does not support aggregate operator MAX".
I'm having the same issue. Is this a bug? Is there a workaround?
Can't you just use the LastActivityDate field on contact? e.g.
select name,lastActivityDate from contact
I don't think so. My use case is something like this:
SomeIds is a set of Account Ids. Any suggestions?