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
beingofhabitsbeingofhabits 

Map of aggregated by 2 fields result

Hello
 
So, we are able to do something like this
Map<String, AggregateResult> aggregations =  new Map<String, AggregateResult> ([SELECT  Status Id, COUNT(Id)QTY FROM Case GROUP BY Status   ]);
But is there any options to do the same with at least 2 aggregated and  grouped fields?
I mean something like the following
Map<String, Map<String,AggregateResult>> aggregations =  new Map<String, Map<String, AggregateResult>> ([SELECT  Status Id, Department__c dId, COUNT(Id)QTY FROM Case GROUP BYStatus, Department__c  ]);
And if not, is the manually written parser the only solution?

Have a nice day!
Best Answer chosen by beingofhabits
Jolly_BirdiJolly_Birdi
Hello Mate,

Please check the below Code function:
 
public static Map<String, Map<String,AggregateResult>>  getAggregationResult(){
	Map<String, Map<String,AggregateResult>> returnResults = new Map<String, Map<String,AggregateResult>>(); 
	List<AggregateResult> Results = [SELECT  Status Id, Department__c dId, COUNT(Id) QTY FROM Case GROUP by Department__c   order by Status];
	
	String OldStatus, NewStatus, OldDepartment, NewDepartment;
	Map<String,AggregateResult> addList = null;
	
	for(AggregateResult ar : Results){
		String NewStatus = (String)ar.get('Id');
		String NewDepartment = (String)ar.get('dId');
		
		if(addList == null){
			addList = new Map<String,AggregateResult>();
			addList.put(NewDepartment,ar);
		}
		else if(OldStatus == NewStatus){
			addList.put(NewDepartment,ar);
		}	
		else if(OldStatus != NewStatus){
			returnResults.put(OldStatus,addList);
			addList = new Map<String,AggregateResult>();
			addList.put(NewDepartment,ar);
		}	
		
		OldStatus = NewStatus;
		OldDepartment = NewDepartment;
	}
	
	returnResults.put(OldStatus,addList);
	
	return returnResults;
}



Please like and mark this as best answer if you find it Positive.

Thanks,
Jolly Birdi