我需要一个返回序列的第一个元素的 FIRST 聚合函数,我将把它与 HAVING 子句一起使用。
这是一个可以看作是我之前的问题的延续:FIRST aggregate function which I can use with HAVING 子句的问题。
事实证明,只有聚合函数才能解决我的问题,所以我尝试创建一个:
[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined, //use clr serialization to serialize the intermediate result
IsInvariantToNulls = true, //optimizer property
IsInvariantToDuplicates = false, //optimizer property
IsInvariantToOrder = false, //optimizer property
MaxByteSize = 8000) //maximum size in bytes of persisted value
]
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() {
// Put your code here
return new SqlInt32(int.Parse(allValues.Split(',')[0]));
}
// This is a place-holder member field
private SqlInt32 var1;
public void Read(System.IO.BinaryReader r) {
allValues = r.ReadString();
}
public void Write(System.IO.BinaryWriter w) {
w.Write(this.allValues);
}
}
这就是我使用它的方式:
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;
它有时会返回正确的结果,有时不会,我不确定我是否正确实施了它。考虑到我的要求,如果我做对了,有什么想法吗?