I don't know offhand of a complete solution. You should be able to eliminate the first aggregate call by doing something like this:
Map<ID, ParentObject__c> ParentObjectMap = new Map<ID, ParentObject__c>(
[SELECT ID, ChildObjects_Created__c, ChildObjects_Unassigned__c,
ChildObjects_Revenue__c, (Select ID from ChildObjects) FROM ParentObject__c
WHERE ID IN :SetOfParentObjectIDs]);
(I'm assuming the relationship name is ChildObjects). You can then look at ParentObjectMap.get(someid).ChildObjects.Size() to find the number of child objects on a given parent.
In terms of the other two aggregate queries - here's a trick that might work for you:
Create two new numeric formula fields on the ChildObject. Set the first field to 1 if the Field__c field is set to 'Unassigned', zero otherwise. Set the second field to the value of the Net_Price_c field if the Status_c field is 'Paid', zero otherwise.
Now, you should be able to do a single aggregate query along the lines of:
AggregateResult[] groupedCountUnassigned = [SELECT COUNT(id), SUM(firstformulafield),
SUM(secondformulafield) FROM ChildObject__c WHERE ParentObjectID__c IN
:SetOfParentObjectIDs GROUP BY ParentObjectID__c];
In effect, you're moving the filter condition from the SOQL query into the formula field (where it doesn't cost you against Apex limits). It is costing you a couple of fields, and depending on the amount of data you are dealing with could make a selective query non-selective, but for some applications, it can be a good solution.
Dan
Can you please mention which SOQL is returning empty?
As I have seen your code the problem is in this line of insertTestData_AccountsAndOpportunities() method:
opps = [SELECT Id, AccountId, RecordTypeId, RecordType.Name, CloseDate, IsClosed FROM Opportunity WHERE Account.Name IN :accountsMap.keySet()];
The accountsMap contains (Id, Account) which is populated from this query:
Map<Id, Account> accountsMap = new Map<Id, Account>([SELECT Id, Name, Type FROM Account WHERE Name IN :accountNames]);
that's why it will return empty and you are putting this opps into the map below:
finalMap.put('Opportunity',opps);
Let me know my guess is right?
Best Answer
Rather than performing the query for each record that comes into your trigger - which is what it sounds like you're doing. What you need to do is perform 1 much broader query that gets back all of the likely candidates for duplicate records. Then do the duplicate processing in Apex using a composite key.
For example: