I have a weird requirement which I need to use inside my Stored Procedure in SQL Server 2008 R2.
I need a FIRST aggregate function which returns the first element of a sequence and I will use that with HAVING clause.
Let me give you 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 see, we have a table and some dummy values. Inside the SELECT query, we group the categories together and sum the price of the products up.
This query returns the following result:
CategoryName TotalPrice
---------------- ----------------
Cat1 345.52
Cat2 12.34
Cat3 25.43
What I need here is something like this:
SELECT ft.CategoryName, SUM(ft.Price) FROM @fooTable ft
GROUP BY ft.CategoryName
HAVING GetFIRST(MinAllow) >= @minAllowParam;
In that our case with a query something like this, we should be able to select 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);
As the INSERT INTO @fooTable VALUES(1, 'Cat1', 'Product1', 2, 112.2); record is the first element of a sequence and has the value of 2 for MinAllow column, Cat1 should be out of scope here. On the other hand, INSERT INTO @fooTable VALUES(5, 'Cat3', 'Product5', 1, 13.00); record has the value of 1 for MinAllow column but is the second element of the sequence. So, Cat3 is safe and can be selected.
Note:
MINorMAXis not what I am looking for!
I know that this example logically does not make sense but I have a situation which it totally does and hard to explain here on the other hand.
Any thoughts?
Edit:
I am assuming that I can achieve what I want here by creating a CLR
User-Defined Aggregate Function but I do not want to do this if there
is any other choice
How about
I know not a very elegant query. Maybe I can tweak it a little if I work on it a little longer!
Edit: Ok the inner most subquery should be unnecessary. This should also work: