Search code examples
dynamics-crmfetchxmldynamics-crm-webapi

Select a count of contacts from accounts using FetchXML


Does anyone know the FetchXML format in order to select the count of contacts for accounts?

For example, I would have a list of AccountID's that I would us an IN filter for and I would just require the AccountID and the integer count of the contacts for that account.

Solved (see below) with a minor change to group by accounts. Here is the final fetchxml that I used:

<fetch xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" aggregate="true" distinct="false" mapping="logical"> 
<entity name="contact">
<attribute name="contactid" alias="recordcount" aggregate="count" />
<link-entity name="account" to="accountid" alias="accountid">
<attribute name="accountid" alias="accountid" groupby="true" />
<filter>
<condition attribute="accountid" operator="in">
<value>708039fd-f7b1-e811-a973-000d3af4a510</value>
<value>0a8139fd-f7b1-e811-a973-000d3af4a510</value>
<value>428139fd-f7b1-e811-a973-000d3af4a510</value>
<value>4a8139fd-f7b1-e811-a973-000d3af4a510</value>
<value>618139fd-f7b1-e811-a973-000d3af4a510</value>
<value>9f8139fd-f7b1-e811-a973-000d3af4a510</value>
<value>ae8239fd-f7b1-e811-a973-000d3af4a510</value>
</condition>
</filter>
</link-entity>
</entity>
</fetch>

Solution

  • You can do an aggregate fetch with a group by on the parentcustomerid.

    <fetch distinct='false' mapping='logical' aggregate='true'> 
        <entity name='contact'> 
            <attribute name='contactid' alias='contact_count' aggregate='countcolumn' /> 
            <attribute name='parentcustomerid' alias='parentcustomerid' groupby='true' />
            <link-entity name='account' from='accountid' to='parentcustomerid'>
                <filter type='and'>
                    <condition attribute='accountid' operator='in'>
                        <value>{00000000-0000-0000-0000-000000000001}</value>
                        <value>{00000000-0000-0000-0000-000000000002}</value>
                    </condition >
                </filter>
            </link-entity> 
        </entity> 
    </fetch>