Select 使用 FetchXML 的帐户中的联系人计数

Select a count of contacts from accounts using FetchXML

有人知道 FetchXML 格式以便 select 帐户的联系人计数吗?

例如,我有一个 AccountID 列表,我将为其使用 IN 过滤器,我只需要 AccountID 和该帐户的联系人的整数计数。

通过对按帐户分组的微小更改解决(见下文)。这是我使用的最终 fetchxml:

<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>

当您 use Rollup field.

时,这很简单

然后就可以方便的查询次数了

<fetch>
  <entity name="account" >
    <attribute name="name"  />
    <attribute name="new_contactcountrollup"  />
  </entity>
</fetch>

更新:

为什么我说 fetchxml 不支持子查询,因为我在考虑第二种解决方案。

--using just JOIN
SELECT a.accountid, count(1) AS [contact count] FROM contact c
INNER JOIN account a
ON c.parentcustomerid = a.accountid
WHERE a.accountid IN  (
'{0ACDC4F5-4885-E811-A967-000D3A1A9407}', '{BA41CEBA-199F-E811-A96B-000D3A1A9EFB}')
GROUP BY a.accountid

--using SUBQUERY
SELECT a.accountid,
    (SELECT Count(1) FROM contact c WHERE c.parentcustomerid = a.accountid) AS [contact count]
    FROM account a
    WHERE a.accountid IN (
'{0ACDC4F5-4885-E811-A967-000D3A1A9407}', '{BA41CEBA-199F-E811-A96B-000D3A1A9EFB}')

您可以对 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>