Use of aggregate, groupby in fetchxml query
In Microsoft Dataverse, FetchXML includes grouping and aggregation features that let you calculate sum, average min, max and count.
groupby is used to get data from CRM and group it based on particular field value. To use group-by we need to use aggregate.
e.g.; If we want to get group accounts based on country and we want count of those country in descending order then we will use fetchXML like below in c#.
string accountNumber = "ANO10052023";
string fetchXML = @"<fetch aggregate='true' distinct='false' mapping='logical'>
<entity name='account'>
<attribute aggregate='countcolumn' alias='country_count' name='new_country'>
<attribute alias='new_country' groupby='true' name='new_country'>
<order alias='country_count' descending='true'/>
<filter type='and'>
<condition attribute='new_accountnumber' operator='eq' value="' + accountnumber + @'"/>
</filter>
</entity>
</fetch>";
EntityCollection accountCollection = service.RetrieveMultiple(new FetchExpression(fetchXML));
if(accountCollection.Entities.Count > 0)
{
var c = accountCollection.Entities[0];
int countryCount = (Int32)((AliasedValue)c["country_count"]).Value; //will give max count of groupby country
string countryName = (string)((AliasedValue)c["new_country"]).Value; //will give country name
Console.WriteLine("Count : " + countryCount + " Country : " + countryName);
}
"countcolumn" gives number of records that have value in attribute, however "count" will give total number of records.
Comments
Post a Comment