I need a FIRST aggregate function that returns the first element of a sequence, and I will use this with a HAVING clause.
This is a question that can be seen as a continuation of my previous question: FIRST aggregation function that I can use with the HAVING clause .
It turns out that only a summary function can solve my problem, so I tried to create it:
[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined,
IsInvariantToNulls = true,
IsInvariantToDuplicates = false,
IsInvariantToOrder = false,
MaxByteSize = 8000)
]
public struct GetFirst : IBinarySerialize {
private string allValues;
public void Init() {
allValues = string.Empty;
}
private void incrementAndAdd(SqlInt32 value) {
allValues += (value.Value.ToString() + ",");
}
public void Accumulate(SqlInt32 Value) {
incrementAndAdd(Value);
}
public void Merge(GetFirst Group) {
}
public SqlInt32 Terminate() {
return new SqlInt32(int.Parse(allValues.Split(',')[0]));
}
private SqlInt32 var1;
public void Read(System.IO.BinaryReader r) {
allValues = r.ReadString();
}
public void Write(System.IO.BinaryWriter w) {
w.Write(this.allValues);
}
}
And here is how I used it:
DECLARE @fooTable AS TABLE(
ID INT,
CategoryName NVARCHAR(100),
Name NVARCHAR(100),
MinAllow INT,
Price DECIMAL(18,2)
);
INSERT INTO @fooTable VALUES(1, 'Cat1', 'Product1', 3, 112.2);
INSERT INTO @fooTable VALUES(2, 'Cat2', 'Product2', 4, 12.34);
INSERT INTO @fooTable VALUES(3, 'Cat1', 'Product3', 5, 233.32);
INSERT INTO @fooTable VALUES(4, 'Cat3', 'Product4', 4, 12.43);
INSERT INTO @fooTable VALUES(5, 'Cat3', 'Product5', 1, 13.00);
INSERT INTO @fooTable VALUES(7, 'Cat4', 'Product7', 1, 15.00);
INSERT INTO @fooTable VALUES(6, 'Cat4', 'Product6', 3, 13.00);
DECLARE @minAllowParam AS INT = 3;
SELECT ft.CategoryName, SUM(ft.Price), dbo.GetFirst(ft.MinAllow) FROM @fooTable ft
GROUP BY ft.CategoryName
HAVING dbo.GetFirst(ft.MinAllow) >= @minAllowParam;
Sometimes it returns the correct result, sometimes not, and I'm completely not sure if I implemented it correctly. Any thoughts if I understood this correctly taking into account my requirements?