question

epoppleton avatar image
epoppleton asked

Generate Unique Group ID's

I want to create a unique identifier based on a possible grouping and can't figure out how to accomplish this.

For example, If I had 3 users named Tom, 2 named Bill and 2 name Suzie, I want to be able to generate via a select query group id's for the users like the list below.

Name   |   ID   |                    
__________________                    
Tom        1,                    
Tom        1,                    
Tom        1,                    
Bill       2,                    
Bill       2,                    
Suzie      3,                    
Suzie      3                    

I currently have a function in MS Access that does this for me, but I can't figure out how to work this out in SQL. Your help is appreciated.

guid
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

RickD avatar image RickD commented ·
How is the identifier unique?!?
0 Likes 0 ·
Benjamin avatar image
Benjamin answered

Here's one simple way to do this.

SELECT Name, CHECKSUM(name) AS ID            
FROM YourTable            
ORDER BY Name            

Here's another way which requires SQL Server 2005 or above.

SELECT Name, RANK() OVER (ORDER BY Name) AS ID            
FROM YourTable            
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

TG avatar image
TG answered

So each group of names will have a single groupID? Here's a couple ways:

--assumes you have a unique single column Primary Key            
select t.Name            
       ,g.GroupID            
from   (            
       select name            
              ,min(PK_value) as GroupID            
       from   YourTable            
       group by name            
       ) g            
join   yourTable t            
       on t.name = gID.name            
            
--If no PK and sql 2005 or later            
select t.Name            
       ,g.GroupID            
from   (            
       select name, row_Number() over (order by name) as GroupID            
       from   YourTable            
       group by name            
       ) g            
join   yourTable t            
       on t.name = gID.name            
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.