Search code examples
dynamics-crm-2011maxaggregatefetchxml

Aggregate function with FetchXML


I need to fetch the entity who has the max date in a certain field. I tried the code below with Stunnware but it gives me an error that the MAX function is invalid.

  <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
    <entity name='field1'>
      <attribute name='field2' />
      <attribute name='field3' />
      <attribute name='field4' />
      <order attribute='field1' descending='false' />
      <link-entity name='contact' from='field1' to='otherfield' alias='ac'>
          <filter type='and'>
          <condition attribute='field5' operator='eq' value='123456' />
           </filter>
      </link-entity>
     <link-entity name='secondentity' from='field2' to='otherfield' visible='false' link-type='outer' alias='a_6c61a84be522e31194080050569c4325'>
         <attribute name='date' alias='maxdate' aggregate='max' />
      </link-entity>
   </entity>
   </fetch>

Can you help point me to the mistake i'm doing ?


Solution

  • It turned out that it will not work:

    There has been several problems in my query:

    1- According to Paul Way's reply, my fetch xml was missing aggregate="true"

    2- Aggregate functions won't work with Order attribute

    3- If I'm going to retrieve attributes while using the aggregate function I have to groupby them and add an alias

    4- Aggregate function MAX cannot be applied on Date types.

    So my other solution is to retrieve all the dates in descending order and then I will use the first entity retrieved.