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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With