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
WildManWildMan 

I would like to use a SOQL query to daily assess all accounts based on opportunities The account with the highest opportunity value over the past year is ranked 1 and so on. Any Idea ?

Malika Pathak 9Malika Pathak 9

Hi WildMan,

please find the solution

public class HighestOppAccount {
    public static void AccountSOpportunity(){
        List<Account> accList=new List<Account>();
        accList=[SELECT Id,Name,(SELECT Id FROM Opportunities) FROM Account LIMIT 1000];
        Map<Integer,Account> mapvalue=new Map<Integer,Account>();
        for(Account acc:accList){
            if(acc.Opportunities.size()>0 && !mapvalue.containsKey(acc.Opportunities.size())){
                mapvalue.put(acc.Opportunities.size(),acc);
            }
        }
        Set<Integer> intList=new Set<Integer>(mapvalue.keySet());
        
        integer j=1;
        List<Integer> sortList=new List<Integer>(intList);
        sortList.sort();
        system.debug('sorted'+sortList);
        for(Integer i=sortList.size()-1;i>=0;i--){
            system.debug(mapvalue.get(sortList[i]).Name +'\t'+'rank  '+ j++ +'\t'+sortList[i]);
       }
        
    }
}

If you find this solution is helpful for you please mark the best answer
WildManWildMan
Thanks for the code. but I need a simple query. in that query I need the total amout of an opp related to an account  over the past year . The result should be ranked by the hightest value (DESC)
WildManWildMan
My query should look like this : SELECT Name, AccountId, SUM(Amount) FROM Opportunity WHERE Date=LAST_YEAR GROUP BY "Rank"DESC But I don't know how to do !