+ Start a Discussion

Help with a SOQL's query (SUM)


I need to do a query in SOQL like this in SQL:

Select SUM(field1), field2 From Table Where condition Group By field2

I Know that It isn't posible, but is there a way to do something seemed?

I would like do something not to calculate this "SUM" by code.

Ron HessRon Hess
you have to write a for loop to calculate this sum()
It's not entirely clear what you are trying to calculate, but Tom Tobin's blog posting has a tip for calculating a sum on groups in a grouping.

Hope this helps.

- Rick Greenwald
Developer Evangelist

Hi there,


is there any way to loop through the subresult from apex?


i got a statement "select Id, (select Amount_Hrs__c from ContractQuotas__r)  from contract" with multiple subrows which have to be summed up as no roll up is helpfull here. usually i'd loop through the list i get back from the query and access the fields via listname.get(position).Fieldname. But i cannot find a way to loop through the subquery-results ...


Any hint would be very helpfull. :robothappy:






the link seems to be broken or false ... am i wrong?



public void ShowContractEntries(){
string myString = acc.Id; contrEntries =[select Id, StartDate, Quota__c, Iteration__c, Status, EndDate2__c, EndDate, ContractTerm, CreatedDate, Account.Type, ContractNumber, Type__c, End_User__r.Name, ContractQuotaUsed__c, (select Amount_Hrs__c from ContractQuotas__r) from contract where Status = 'Activated' and AccountId =: myString.substring(0,15) order by CreatedDate DESC]; for(integer i=0;i<contrEntries.Size();i++){ for(integer s =0; s < contrEntries.get(i).ContractQuotas__r.size();s++){
contrEntries.get(i).ContractQuotas__r.get(s).Amount_Hrs__c); hpc = hpc + contrEntries.get(i).ContractQuotas__r.get(s).Amount_Hrs__c;
} contrEntries.get(i).ContractQuotaUsed__c = hpc; hpc =0.0; } update contrEntries; }


Done :) Very simple to loop through the subquery items to sum up something up ... wasn't that obvious too me :)