Bipin,
Thanks for this information about aggregate functions in FetchXML. I'm still learning my way around FetchXML so I usually have to use the FetchXML Builder paired with SQL 4 CDS, but I can't get it to transform this query from SQL into FetchXML.
Can the following query be transformed to FetchXML? If so, would you be able to help me construct it properly? In SQL 4 CDS it seems to break it into 3 separate FetchXML queries when you look at the execution plan and I don't know the proper way to combine them into one FetchXML query.
The successful SQL Query I'm trying to transform:
SELECT opp.opportunityid
,opp.name
,opp.customeventtypename
,opp.ownerid
,opp.owneridname
,opp.statecodename
,opp.totalattendance
,A.MaxArrivalDateTime
FROM opportunity opp
INNER JOIN
(
SELECT c.opportunity
,max(c.arrivaldatetime) MaxArrivalDateTime
FROM oppchildrecords c
GROUP BY c.opportunity
)A ON (A.opportunity = opp.opportunityid)
WHERE opp.customeventtypename = 'EventX'
AND opp.statecodename = 'Open'
AND opp.totalattendance <> '0'
AND opp.totalattendance is not null
AND A.MaxArrivalDateTime <= DATEADD(day, -2, GETDATE())
What SQL 4 CDS does when I try to see the display the FetchXML on execution:

The three individual FetchXML Queries it produces in that execution plan above are:
Merge Join:
<fetch xmlns:generator='MarkMpn.SQL4CDS'>
<entity name='opportunity'>
<attribute name='opportunityid' />
<attribute name='name' />
<attribute name='customeventtype' />
<attribute name='ownerid' />
<attribute name='statecode' />
<attribute name='totalattendance' />
<link-entity name='customeventtype' to='customeventtype' from='customeventtypeid' alias='opportunity_customeventtype' link-type='outer' />
<filter>
<filter>
<filter>
<condition attribute='customeventtype' entityname='opportunity_customeventtype' operator='eq' value='EventX' />
<condition attribute='statecode' operator='eq' value='0' />
</filter>
<condition attribute='totalattendance' operator='ne' value='0' />
</filter>
<condition attribute='totalattendance' operator='not-null' />
</filter>
<order attribute='opportunityid' />
</entity>
</fetch>
T-SQL Try Catch:
<fetch xmlns:generator='MarkMpn.SQL4CDS' aggregate='true'>
<entity name='oppchildrecords'>
<attribute name='opportunity' alias='opportunity' groupby='true' />
<attribute name='arrivaldatetime' alias='MaxArrivalDateTime' aggregate='max' />
<order alias='opportunity' />
</entity>
</fetch>
Hash Match Aggregate:
<fetch xmlns:generator='MarkMpn.SQL4CDS'>
<entity name='oppchildrecords'>
<attribute name='opportunity' />
<attribute name='arrivaldatetime' />
</entity>
</fetch>
Thank you!