I'm comparing my custom CLR aggregate vs AVG (SQL Server 2017). My queries are:
SELECT groupId, Helpers.CustomCLR(value)
FROM table
group by groupId
SELECT groupId, AVG(value)
FROM table
group by groupId
And CLR is
[Serializable]
[SqlUserDefinedAggregate(
Format.Native, //use clr serialization to serialize the intermediate result
IsInvariantToNulls = true, //optimizer property
IsInvariantToDuplicates = false, //optimizer property
IsInvariantToOrder = true)
]
[StructLayout(LayoutKind.Sequential)]
public class CustomCLR
{
float a = 2;
public void Init()
{
}
public void Accumulate(SqlSingle value)
{
}
public void Merge(CustomCLR other)
{
}
public double? Terminate()
{
return a;
}
}
Execution plans are quite different, though. CLR query does row mode sorting and AVG query does batch mode hash match. How to make CLR aggregate behave like AVG one?