+ Start a Discussion
Nitin sharma 424Nitin sharma 424 

Aggregate functions

Hi All,I have used aggregate furnctions for the Amount field on the opportunity object and udpated the Related Account obect with the results.
However,Salesforce documentation says

Aggregate function results on currency fields default to the system currency.

I have created currency fields on the Account object and I thought that I will be able to assign values from currency amount field to the currency fields on the Account object.But it gave me an error that object fields cannot be convrted to Decimal fields.I am not sure how it became a decimal field when I have created it as a currency field..

But when I typecased to amount field to decimal in the below given code then it worked fine.

Am I  missing somthing here.?
Need to understand,Why system made me typecast Opportunity Amount  field to Decimal type to save value in the currency field on the Account Object.

Can somebody please explain.?


Trigger UpdatingAccountWithOppInformation on Opportunity (After insert,After Update)
{
List<Account>Acc=new list<account>();
Map<ID,Opportunity>OppRecord=new Map<Id,Opportunity>();
Set<Id>SetOfIdsOfAccountRecords=new set<id>();    
For(Opportunity Opp:trigger.new)
{
If(Opp.AccountId!=null)
{
 
    
//OppRecord.put(opp.accountid,opp);
SetOfIdsOfAccountRecords.add(Opp.accountid);
    
}
}
    
AggregateResult [] Result=[Select AccountId Id,Avg(Amount) Amt, Count(ID) countOfOpp,MIN(Amount) MinAmount,Max(Amount) MaxAmount,Sum(Amount) TotalOfAppOpps from opportunity where AccountId in:SetOfIdsOfAccountRecords Group By AccountId];  
for(AggregateResult rope:result)
{

Acc.add(New Account(Id=(Id)rope.get('Id'),Average_Opportunity_Amount__c=(Decimal)rope.get('Amt'),Count_Of_Opportunities__c=(Decimal)rope.get('countOfOpp'),Opportunity_with_Min_Amount__c=(Decimal)rope.get('MinAmount'),Opp_with_Max_Amount__c=(Decimal)rope.get('MaxAmount'),Sum_Of_All_Opportunities__c=(Decimal)rope.get('TotalOfAppOpps')));

}
Update Acc;
}

    


 
Shubham4462Shubham4462
Hello Nitin,

Please check the below article it is offical salesforce documentation which states that currency field should be stored in the Decimal Varriable, so the currency fields are treated as Decimal in apex.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_primitives.htm
Nitin sharma 424Nitin sharma 424
I got it.Thanks for your reply.