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
test codetest code 

How To Get Sum Of a field in a query used in apex class

hi,i am trying to get total of a custom field i.e sum of premium,but the problem is whenever i m using SUM its throwing error.i have pasted my code in that code only i m using the function.When i m grouping the fields also its throwing error.i used aggregate methods also.Can anyone tell how to get the sum??

 

 

 

public class MyPolicy{
    public MyPolicy(ApexPages.StandardController controller) {

    }


        public List<Policy__c> getMyPolicy() {
Policy__c[] Pol = [SELECT name,Sum_Of_Premium__c,Channel_Name__r.Target__c,Channel_Name__r.name from Policy__c ];
 return Pol;
    }

}

Navatar_DbSupNavatar_DbSup

Hi,

 

Try the below SOQL query

ggregateResult[] groupedResults  = [SELECT SUM(Amount)aver FROM Opportunity];

Object avgAmount = groupedResults[0].get('aver');

 

For more detail follow below links:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_agg_fns.htm

http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_soql_select_agg_functions.htm

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

test codetest code

its not working i tried like this way also.

its showing error as Non-void method might not return a value or might have statement after a return statement.

sfdcfoxsfdcfox

The problem isn't your query. It is related to the fact that you have a return statement that doesn't return a value and/or you have code after an unconditional return statement. Could you post your code?

test codetest code

hi here is the code in which i m trying to sum the custom field Sum Of Premium.I used Sum function and group function also in that code but no results.can you tell me how to achieve this???

 

public class MyPolicy{
    public MyPolicy(ApexPages.StandardController controller) {

    }


        public List<Policy__c> getMyPolicy() {
Policy__c[] Pol = [SELECT name,Sum_Of_Premium__c,Channel_Name__r.Target__c,C​hannel_Name__r.name from Policy__c ];
 return Pol;
    }

}