Aggregate Function on Uniqueidentifier (GUID)

Heinzi picture Heinzi · May 20, 2011 · Viewed 27.3k times · Source

Let's say I have the following table:

category | guid
---------+-----------------------
   A     | 5BC2...
   A     | 6A1C...
   B     | 92A2...

Basically, I want to do the following SQL:

SELECT category, MIN(guid)
  FROM myTable
 GROUP BY category

It doesn't necessarily have to be MIN. I just want to return one GUID of each category. I don't care which one. Unfortunately, SQL Server does not allow MIN or MAX on GUIDs.

Of course, I could convert the guid into a varchar, or create some nested TOP 1 SQL, but that seems like an ugly workaround. Is there some elegant solution that I've missed?

Answer

K Biel picture K Biel · Oct 27, 2011

Just cast it as a BINARY(16).

SELECT category, MIN(CAST(guid AS BINARY(16)))
FROM myTable
GROUP BY category

You can cast it back later if necessary.

WITH CategoryValue
AS
(    
    SELECT category, MIN(CAST(guid AS BINARY(16)))
    FROM myTable
    GROUP BY category
)
SELECT category, CAST(guid AS UNIQUEIDENTIFIER)
FROM CategoryValue