0
votes

Fairly new to APEX (Salesforce development) and i found an issue with one of SOQL statements...

Error Message

This is the code that is creating the problem.. i did some research and i found that i need to create a set of id's instead of using another select statement for OpportunityId and then just reference it on the query...

String sumAvgQuery = 'SELECT StageName, COUNT(ID) opps, SUM(Amount) total, AVG(SVC_Svc0StageAge__c) Svc0, AVG(SVC_Svc1StageAge__c) Svc1, ' +
                                'AVG(SVC_Svc2StageAge__c) Svc2, AVG(SVC_Svc3StageAge__c) Svc3, AVG(SVC_Svc4StageAge__c) Svc4, ' + 
                                'AVG(SVC_Svc5StageAge__c) Svc5, AVG(SVC_Svc6StageAge__c) Svc6, AVG(SVC_Svc7StageAge__c) Svc7, ' +
                                'AVG(SVC_Svc8StageAge__c) Svc8, AVG(SVC_Svc9StageAge__c) Svc9 ' +
                                'FROM Opportunity ' +
                                'WHERE StageName in (' + BTG_Utility.OPPORTUNITY_STAGES + ') ' +
                                'AND ID in (SELECT OpportunityId FROM OpportunityTeamMember WHERE UserId = \'' + String.escapeSingleQuotes(userId) + '\') ' +
                                ((cluster != null && cluster != '') ? 'AND SVC_AccountCluster__c = \'' + String.escapeSingleQuotes(cluster) + '\' ' : '') +
                                ((region != null && region != '') ? 'AND SVC_AccountRegion__c = \'' + String.escapeSingleQuotes(region) + '\' ' : '') +
                                ((country != null && country != '') ? 'AND CARE_AccountCountry__c = \'' + String.escapeSingleQuotes(country) + '\' ' : '') +                                                            
                                ((product != null && product != '') ? ' AND Id in (SELECT OpportunityId FROM OpportunityLineItem Where Product2.Name = \'' + String.escapeSingleQuotes(product) + '\' and Opportunity.IsClosed = FALSE) ' : '') +
                                'GROUP BY StageName)';

Can you please help me on how to do this ? Really appreciate the help !

1

1 Answers

0
votes

If you want to use a collection like a Set in Apex you need to populate the set first, then you can use the variable name in your SOQL query with a : in front of it.

So for example:

// First populate the Set with ID's using SOQL
set<Account> inputSet = new set<Account>([SELECT Id FROM Account LIMIT 5]);

//Alternatively manually populate the set
// set<String> inputSet = new set<String>();
// List<Account> accounts = new List<Account>([SELECT custom_id__c FROM Account LIMIT 5]);
// for (Account acc : accounts) {
//      inputSet.add(acc.custom_id__c);
// }
System.debug('inputSet: ' + inputSet);

// Use the set with the data 

List<Contact> contacts = [SELECT id FROM Contact where custom_id__c in :inputSet];
System.debug('contacts: ' + contacts);

Hope that helps.

Mohamed Imran