Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Generate Group ID's

Author  Topic 

epoppleton
Starting Member

5 Posts

Posted - 2009-10-28 : 12:28:41
I need to generate a group ID on the fly.

For example, if I had 2 users named Bill, 2 named Tom and 3 named Janet, I need to generate id's for each group of names. How can I do this in sql?

Name | ID
Bill | 1
Bill | 1
Tom | 2
Tom | 2
Janet | 3
Janet | 3
Janet | 3

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-10-28 : 12:36:06
Something like this:
select
t1.Name,
dt.groupId
from your_Table t1
join
(select Name, row_number() over (partition by Name order by Name) as groupId from your_Table group by Name)dt
on dt.Name = t1.Name


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

epoppleton
Starting Member

5 Posts

Posted - 2009-10-28 : 13:24:55
Thanks Webfred, I have a table called Business, and I tried your suggestion on the field BusinessName like this:

select
t1.BusinessName,
dt.groupId
from tblBusiness t1
join
(select BusinessName, row_number() over (partition by BusinessName order by BusinessName) as groupId from tblBusiness group by BusinessName)dt
on dt.BusinessName = t1.BusinessName


The ID's all came back as "1". Did I do something wrong?
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-10-28 : 13:36:43
Oh I'm sorry!
remove that: "partition by BusinessName "


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

epoppleton
Starting Member

5 Posts

Posted - 2009-10-28 : 13:38:25
Worked beautifully, thank you so much.
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-10-28 : 13:41:31
welcome


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

epoppleton
Starting Member

5 Posts

Posted - 2009-10-28 : 17:28:35
Webfred, let me add to this and see if you can help. If I then wanted to add another column to my results that then numbered sequentially the groupid, how would I do that? i.e.


Name | ID | Seq
Bill | 1 | 1
Bill | 1 | 2
Tom | 2 | 1
Tom | 2 | 2
Janet | 3 | 1
Janet | 3 | 2
Janet | 3 | 3
Go to Top of Page

epoppleton
Starting Member

5 Posts

Posted - 2009-10-28 : 19:16:23
Nevermind, I got it. Thanks again for your help.


select
tblbusiness.businessname,
dt.ref,
row_number() over (PARTITION BY ref ORDER BY ref) as 'seq'
from tblbusiness
join
(select businessname, row_number() over (order by businessname) as ref from tblbusiness group by businessname) dt
on dt.businessname = tblbusiness.businessname
Go to Top of Page
   

- Advertisement -