Skip to main content What is Dynamics 365? Guided tours Customer stories Try our products CRM ERP Sales Service Sales Customer Insights Customer Service Contact Center Field Service Supply Chain Management Commerce Finance Project Operations Human Resources Business Central Pricing Business application topics Training & certifications Migrate to the cloud Documentation Events Dynamics 365 Blog Product updates Onboarding and implementation Community Find a partner Software Development Companies Partner resources Microsoft Marketplace Product documentation Technical support On-premises product support Contact us Try for free Sign in
  • 1 min read

Support for COUNT(DISTINCT) in Fetch XML queries


We have made a couple of enhancements to the aggregate query feature of Fetch XML. These updates have shipped for version 4.0 as part of UR2 and for version 3.0 as documented in KB Article 960079. So far we only supported the count aggregate function which essentially did a count(*) on the base table of the entity.

We have enhanced this functionality to add a new aggregate operation countcolumn which now performs the SQL count operation for a given column. It also support the distinct keyword which only counts unique columns. If the distinct keyword is not specified with a countcolumn aggregate, its value defaults to false.

Here is a table that summarizes the Fetch aggregate types and its equivalent SQL translation:

CRM Fetch XMLSQL
<attribute name=’address1_city’ aggregate=’count’ alias=’citycount’ />SELECT COUNT(*) AS ‘citycount’ FROM Account
<attribute name=’address1_city’ aggregate=’countcolumn’ alias=’citycount’ />SELECT COUNT(address1_city) AS ‘citycount’ FROM Account
<attribute name=’address1_city’ aggregate=’countcolumn’ alias=’citycount’ distinct=’true’ />SELECT COUNT(DISTINCT address1_city) AS ‘citycount’ FROM Account

Key: Existing Feature, New Feature

Here are a couple of examples for using these features:

Query to return a count of all Accounts which have a county specified in their address.

1: Query to return a count of all Accounts which have a county specified in their address.
   2: 
   3:     
   4:         
   5:     
   6: 

Query to return a count of states in which we have an account. This uses the distinct keyword which counts a state only once.

1: 
   2:     
   3:         
   4:     
   5: 

Get started with Dynamics 365

Drive more efficiency, reduce costs, and create a hyperconnected business that links people, data, and processes across your organization—enabling every team to quickly adapt and innovate.