I have a strange requirement that I need to use inside my stored procedure in SQL Server 2008 R2.
I need a FIRST aggregate function that returns the first element of a sequence, and I will use this with a sentence HAVING.
Let me give an example:
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', 2, 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);
DECLARE @minAllowParam AS INT = 3;
SELECT ft.CategoryName, SUM(ft.Price) FROM @fooTable ft
GROUP BY ft.CategoryName;
As you can see, we have a table and some dummy values. Inside the query, SELECTwe group the categories together and summarize the product prices up.
This query returns the following result:
CategoryName TotalPrice
---------------- ----------------
Cat1 345.52
Cat2 12.34
Cat3 25.43
I need something like this here:
SELECT ft.CategoryName, SUM(ft.Price) FROM @fooTable ft
GROUP BY ft.CategoryName
HAVING GetFIRST(MinAllow) >= @minAllowParam;
In our case, with a query like this, we should be able to select the following results:
INSERT INTO @fooTable VALUES(2, 'Cat2', 'Product2', 4, 12.34);
INSERT INTO @fooTable VALUES(4, 'Cat3', 'Product4', 4, 12.43);
INSERT INTO @fooTable VALUES(5, 'Cat3', 'Product5', 1, 13.00);
INSERT INTO @fooTable VALUES(1, 'Cat1', 'Product1', 2, 112.2); 2 MinAllow, Cat1 . , INSERT INTO @fooTable VALUES(5, 'Cat3', 'Product5', 1, 13.00); 1 MinAllow, . , Cat3 .
: MIN MAX , !
, , , , .
?
Edit:
, , , CLR User-Defined Aggregate Function, ,