0
for(bank__c parentSetObj: [Select Id, Name, Count_of_Credit_Cards__c, (Select Id, bank__c,amount__c From credit_card__r ) From bank__c Where Id IN:accSetId]){

as aggregate functions are not allowed on inner queries then how to get the sum of amount in the above query to update custom rollup summary field on bank__c.

1 Answer 1

1

You could simply calculate the sum with Apex (instead of relying on the SOQL query to do it for you), but in this case it looks like you can probably re-arrange your query so that there is no inner query.

So instead of
SELECT Id, (SELECT Id FROM Children__r) FROM Parent WHERE Id IN :parentIds

You can base the query off of your child object
SELECT Id FROM Child WHERE ParentId IN :parentIds

Since the information you're looking to gather is now the only part of the query, you can use COUNT() and GROUP BY
SELECT COUNT(Id), ParentId FROM Child WHERE ParentId IN :parentIds GROUP BY ParentId

The big thing to be aware of is that you'll only get a count for parent records that have at least one child record. If you want to be able to update the parent record when it loses its last child, you'll want to iterate through the parent Ids and populate a Map with a record with a default value (like 0).

Map<Id, Parent> parentsToUpdateMap = new Map<Id, Parent>();

for(Id parentId :parentIds){
    parentsToUpdateMap.put(parentId, new Parent(Id = parentId, Count__c = 0));
}

for(AggregateResult ar :/* aggregate query here */){
    parentsToUpdateMap.get((Id)ar.get('ParentId')).Count__c = (Integer)ar.get(<something like 'expr0' or the field alias in your SOQL>);
}

update parentsToUpdateMap.values();
2
  • thanks instead of going for aggregate in soql , used apex and map to create custom rollup summary field ,as later soql aggregate will hurt in governor limits. Commented Nov 6, 2021 at 17:06
  • @Codewithadiee In either case, you still need to use a query if you want reliable data (doing something like value += additionalValue will double-add if you have a field update from workflow, flow, or process builder (any of which will cause your update triggers to run again). Letting SOQL take care of summing things is generally the preferred approach.
    – Derek F
    Commented Nov 6, 2021 at 17:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .