Friday 2 October 2015

Aggregate FetchXML Queries in CRM 2011/2013/2015

Hi,

Today I got a requirement to calculate the sum of the invoice records in CRM.

Normally, we can do retrieve all records from CRM and loop through each record and calculate the sum of the total amount.

Here is the way to do using Fetch XML where looping is not required.

string strFetchXML = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' aggregate='true'>
   <entity name='invoice'>
       <attribute name='totalamount' aggregate='sum' alias='inv.totalamount'/>
       <filter type='and'>
           <condition attribute='statecode' operator='eq' value='0'/>
       </filter>
    </entity>
</fetch>";
EntityCollection entInvColl = iService.RetrieveMultiple(new FetchExpression(strFetchXML));
Entity entInvoice = entInvColl.Entities[0];
AliasedValue avTotalAmount = (AliasedValue)entInvoice.Attributes["inv.totalamount"];
Money mnyValue = (Money)(avTotalAmount.Value);
decimal decValue = mnyValue.Value;

Hope this helps

--
Happy CRM'ing

Gopinath

1 comment:

  1. Hi Gopi, where you added all invoice total amount in your code. Can you please highlighted it?
    Thanks,
    Andy

    ReplyDelete