all groups > sql server (alternate) > february 2006 >
You're in the

sql server (alternate)

group:

Group By Query Help



Group By Query Help wackyphill NO[at]SPAM yahoo.com
2/28/2006 1:28:36 PM
sql server (alternate): Can you group by a value returned by a UDF? Example:

SELECT Col1, SUM(Col2), MyFunc(Col3, Col4) AS 'MyResult'
GROUP BY Col1, MyResult

I've had no luck. Can this be done?
Re: Group By Query Help markc600 NO[at]SPAM hotmail.com
2/28/2006 1:36:50 PM
Try this

SELECT Col1, SUM(Col2), MyFunc(Col3, Col4) AS 'MyResult'
GROUP BY Col1, MyFunc(Col3, Col4)
Re: Group By Query Help wackyphill NO[at]SPAM yahoo.com
2/28/2006 2:43:04 PM
I'll give it a try guys. Thanx so much for your responses.
Re: Group By Query Help Erland Sommarskog
2/28/2006 10:38:26 PM
Hugo Kornelis (hugo@perFact.REMOVETHIS.info.INVALID) writes:
[quoted text, click to view]

I tried:

CREATE FUNCTION myfun (@int integer) RETURNS int AS
BEGIN
RETURN ((@int - 10000) % 43)
END
go
SELECT dbo.myfun(OrderID), COUNT(*)
FROM Northwind..Orders
GROUP BY dbo.myfun(OrderID)
go
SELECT myfun, COUNT(*)
FROM (SELECT myfun = dbo.myfun(OrderID)
FROM Northwind..Orders) AS x
GROUP BY myfun
go
DROP FUNCTION myfun

The plans look identical.

However, the derived table saves you from having to repeat a complex
expression, and this is a good thing.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
Re: Group By Query Help Hugo Kornelis
2/28/2006 10:51:02 PM
[quoted text, click to view]

More efficient to call the function just once per row:

SELECT Col1, SUM(Col2), MyResult
FROM (SELECT Col1, Col2, MyFunc(Col3, Col4) AS MyResult
FROM SomeTable) AS Der
GROUP BY Col1, MyResult

--
AddThis Social Bookmark Button