Aggregate FetchXml Queries for Dynamics CRM 2011/2013

Recently needed to figure out ways to find sum of various child entity attribute under a parent entity and came across the following way in FetchXml using which can avoid looping through all child entity collection to do various operations such as:

  • sum
  • avg
  • min
  • max
  • count(*)
  • count(attribute name)

Sample FetchXml for sum:

"<fetch distinct='false' mapping='logical' aggregate='true'> <entity name='entity name'> <attribute name='attribute name' aggregate='sum' alias='alias name'/> </entity> </fetch>"

Result xml will be as follows:

"<resultset morerecords="0"'> 
   <result>
      <alias>aggregate value</alias>
   </result>
</resultset>"

Hope it helps!