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
Brian CersosimoBrian Cersosimo 

Help with a Query

I need to query Contacts that their last opportunity is between a range of dates and the  
Customer_group__c INCLUDES ('SMS MARKETING OPT-IN') 
 
 Opportunities has Customer__c to refer Contacts and CloseDate to check the opp date. 
 
 The problem is that when I try to query something like this, the query takes in mind all opportunities instead of the last one , and I need to use it on a Batch Class so  
Database.getQueryLocator() won't allow me to use aggregate functions on in the query.  

Thank you!

Tables:

Opportunity
+----------------------------+---------------+
|      Customer__c        | CloseDate |
+----------------------------+---------------+
| This is the contact Id |      Date      |
+----------------------------+---------------+

Contact
+----------------------------+-----------------------------------------------------+
|          Id                      |                  Customer_group__c                  |
+----------------------------+-----------------------------------------------------+
| This is the contact Id | Picklist (needs to filter by 'SMS MARKETING OPT-IN' |
+----------------------------+-----------------------------------------------------+
AnkaiahAnkaiah (Salesforce Developers) 
Hi Brain,

As per my understnading, you need to query the closed opportunities related contacts which have costumer groug is 'SMS MARKETING OPT-IN' value.

Am i correct?

Thanks!!
McCuboMcCubo
Hi Brian,
I think and easy way to achive what you want is by using subqueries. Try something like this
SELECT Id FROM Contact WHERE Id IN (SELECT Customer__c FROM Opportunity WHERE CloseDate = LAST_N_DAYS:30) AND Customer_group__c INCLUDES ('SMS MARKETING OPT-IN')