Search code examples
filterdynamics-crmfetchdynamics-crm-2016fetchxml

How to filter using fetch to get accurate results?


I need to get all accounts that have phonecalls in state not open, so I created a query on fetch and got some results.

After checking my results I found that I got all accounts that have minimum 1 phonecall that was not open, but I need to get the accounts that all of their connected phonecalls are not open (can't have even 1 in open state) is it possible to do by fetch ?

** by NOT OPEN I mean state of Canceled or Completed.

Here is my fetch query:

@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
  <entity name='account'>
    <attribute name='name' />                                        
    <order attribute='accountamount' descending='true' />
    <link-entity name='phonecall' from='regardingobjectid' to='accountid' alias='ab'>
      <filter type='and'>
        <condition attribute='statecode' operator='ne' value='0' />
      </filter>
    </link-entity>
  </entity>
</fetch>";

Solution

  • What you are looking for is Unmatch query. This can be achieved in 2 queries using fetchxml.

    First Query: You have to pull all the Accounts with open phonecalls.

    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
      <entity name="account" >
        <attribute name="accountid" />
        <order attribute="accountamount" descending="true" />
        <link-entity name="phonecall" from="regardingobjectid" to="accountid" alias="ab" >
          <filter type="and" >
            <condition attribute="statecode" operator="eq" value="0" />
          </filter>
        </link-entity>
      </entity>
    </fetch>
    

    Second Query: Iterate & pass the first query Account resultset as <value> like below, to filter out them.

    <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
      <entity name="account" >
        <attribute name="name" />
        <attribute name="primarycontactid" />
        <attribute name="telephone1" />
        <attribute name="accountid" />
        <order attribute="name" descending="false" />
        <filter type="and" >
          <condition attribute="accountid" operator="not-in" >
            <value><GUID of ACCOUNT1 with OPEN PHONECALL></value>
            <value><GUID of ACCOUNT2 with OPEN PHONECALL></value>
            <value><GUID of ACCOUNT3 with OPEN PHONECALL></value>
          </condition>
        </filter>
      </entity>
    </fetch>
    

    Read for idea