[SalesForce] how do we query for the Last completed task and Next open task for an account in SOQL

I am trying to get the Last completed task and next open task for a set of accountids.

I can get the Last completed by using the following query

SELECT id, (select activitydate from tasks WHERE isclosed= true order by activitydate  desc limit 1) FROM Account WHERE Id IN : AccountIds  

Any idea how i can get the next open activity (ie, the activity which is open and the nearest to current date)

Best Answer

SELECT Id, 
    (SELECT Id FROM ActivityHistories ORDER BY ActivityDate DESC LIMIT 1), 
    (SELECT Id FROM OpenActivities ORDER BY ActivityDate ASC LIMIT 1) 
FROM Account

You could also tweak the query based on other parameters, but this should be a good start.

Related Topic