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
IPIP 

how to resolve "Illegal assignment from LIST<AggregateResult> to Decimal" error

Hi, I'm trying to assign a result of a query to a variable. but i cannot do like that. following is my code.

 

Public decimal Revenue=[select sum(amount) from opportunity];

 

it throws an error as "Illegal assignment from LIST<AggregateResult> to Decimal "..

 

I've also tried with double instead of decimal. it doesn't work.

 

Please give me a solution for my scenario.

Best Answer chosen by Admin (Salesforce Developers) 
Ankit AroraAnkit Arora

Try this and let me know if it doesn't work for you.

 

List<AggregateResult> groupedResults = [SELECT AVG(Amount)aver FROM Opportunity];
Decimal decimalRevenue = 0 ;
if(groupedResults.size() > 0)
{
    String str = '' + groupedResults[0].get('aver') ;
    decimalRevenue = Decimal.ValueOf(str) ;
    System.debug('decimalRevenue ::::: ' + decimalRevenue) ;
}

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

All Answers

kiranmutturukiranmutturu

when you are trying to aggregate a field like sum(field name) that must be the result of aggregate result object..smiply like this

 

AggregateResult[] groupedResults= [SELECT AVG(Amount)aver FROM Opportunity];

Ankit AroraAnkit Arora

Try this and let me know if it doesn't work for you.

 

List<AggregateResult> groupedResults = [SELECT AVG(Amount)aver FROM Opportunity];
Decimal decimalRevenue = 0 ;
if(groupedResults.size() > 0)
{
    String str = '' + groupedResults[0].get('aver') ;
    decimalRevenue = Decimal.ValueOf(str) ;
    System.debug('decimalRevenue ::::: ' + decimalRevenue) ;
}

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

This was selected as the best answer
Fish FighterFish Fighter

When I try this I get the following error:

 


Save error: line 4:82 no viable alternative at character ''

 

Thanks for your help!

Kelly Strauch 2Kelly Strauch 2
@Ankit Arora Thanks for this answer; it has almost solved my problem.  I'm wondering if there's a mistake in your code though, or if I'm just missing something?

I keep getting an error anytime no records are found by the SOQL query.  My debug log shows me that even for empty queries, the size of groupedResults is 1 -- so the if statement checking for size > 0 isn't catching the null exceptions for me.

Any ideas?  Thanks in advance.
Dana Karaffa 9Dana Karaffa 9
@Ankit Arora I tried your solution but I get the following error message: InvoiceTrigger: execution of AfterUpdate caused by: System.TypeException: Invalid decimal: 48.0 Trigger.InvoiceTrigger: line 20, column 1. Is there a problem when using this in a trigger?