Monday, 29 July 2019

Aggregate Result

Use Case : Contract is having multiple documents attached to the related list 'Notes & Attachment',Get the latest attachment document id for each contract.


The Below Code contains:
1.Set Value Assignment 
2.Map Creation
3.SOQL Group By & Having Clause
4.Aggregate Query 
5.Verifying the size of Aggregate Result/Map/Set values
6.Read the Aggregate Result
7.Add values to the Map  from aggregate result
8.Type Casting Aggregate Result
9.Return Type - Map
10.Reading the Map Value
Note : Aliasing the  SOQL field possible only in Aggregate result
       
public static Map GetContractLatestAttachment(Set ContractIds) //Set Value Assignment
    {
        Map ContractAttachMap = new Map(); //Map Creation
        //Get the latest attachment record ID
        //Aggregate Query 
        //SOQL Group By & Having Clause
        AggregateResult[] contrAttAggResults = [SELECT Max(Id) Id,ParentId  FROM Attachment 
                                                Group By ParentId Having ParentId in:ContractIds];     
        //Verifying the size of AggregateResult values 
        if(contrAttAggResults.size()>0)
        {
            //Read the Aggregate Result
            for(AggregateResult aggResult : contrAttAggResults)
            {
            // Add values to the Map from Aggregate Result  
            // Type Casting Aggregate Result - Id as per map declaration
              ContractAttachMap.put((Id)aggResult.get('ParentId'), (Id)aggResult.get('Id')); 
            }        
        }
        return ContractAttachMap;//Return Type - Map
    }         

       
 
       
public void UpdateContractWithLatestAttachmentId()
{
 Map ContractAttachMap = GetContractLatestAttachment();
 //Reading the Map Value
 if(ContractAttachMap != null)
 attachId = ContractAttachMap.get(conRecord.Id);
}

       
 

2 comments: