Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate Function on Uniqueidentifier (GUID)

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?

like image 921
Heinzi Avatar asked May 20 '11 08:05

Heinzi


People also ask

Can a GUID be a primary key?

GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.

Which functions gives us a GUID number that's unique?

There are two functions using which you can create GUIDs in SQL Server – NewID and NewSequentialID. And there's a data type – "uniqueidentifier" which can be used to store GUIDs. It stores a 16-btye binary value.

What is DB GUID?

The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.

What is datatype Uniqueidentifier?

Uniqueidentifier is a Microsoft SQL Server data type that is used to store Globally Unique Identifiers (GUIDs). It can store 16 bytes of data. The Developer tool treats the Uniqueidentifier data type as String.


1 Answers

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 
like image 170
K Biel Avatar answered Sep 26 '22 09:09

K Biel