April 6, 2007 at 10:59 am
Hi there,
I have a table without unique IDs, and now I want to create a unique numeric ID in a rather special way. The table looks like this right now,
| AreaCode | AreaName | 
| 102 | LittleRock | 
| 102 | GreatArea | 
| 102 | Downtown | 
| 102 | WestSide | 
| 102 | EastSide | 
| 102 | SouthSide | 
| 110 | LittleRock | 
| 110 | GreatArea | 
| 110 | Downtown | 
| 110 | WilliamsTown | 
| 110 | EastSide | 
| 110 | SouthSide | 
| 180 | GeorgeTown | 
| 180 | LittleRock | 
| 180 | GreatArea | 
| 192 | Downtown | 
| 192 | Uptown | 
| 192 | WestSide | 
| 192 | EastSide | 
| 192 | SouthSide | 
And I need something like this,
| AreaCode | AreaName | UniqueID | 
| 102 | LittleRock | 10201 | 
| 102 | GreatArea | 10202 | 
| 102 | Downtown | 10203 | 
| 102 | WestSide | 10204 | 
| 102 | EastSide | 10205 | 
| 102 | SouthSide | 10206 | 
| 110 | LittleRock | 11001 | 
| 110 | GreatArea | 11002 | 
| 110 | Downtown | 11003 | 
| 110 | WilliamsTown | 11004 | 
| 110 | EastSide | 11005 | 
| 110 | SouthSide | 11006 | 
| 180 | GeorgeTown | 18001 | 
| 180 | LittleRock | 18002 | 
| 180 | GreatArea | 18003 | 
| 192 | Downtown | 19201 | 
| 192 | Uptown | 19202 | 
| 192 | WestSide | 19203 | 
| 192 | EastSide | 19204 | 
| 192 | SouthSide | 19205 | 
How do I create this kind of unique ID?
All help is appreciated ![]()
April 6, 2007 at 11:39 am
select
areacode,
areaname ,
unique_id = areacode * 100 + rank() over(order by areacode, areaname)
from table1
April 6, 2007 at 12:30 pm
Thanks Mark,
It works !
But unfortunately I need the two last digits in the unique_id to swith to/begin with 01 after every new AreaCode.
Your SQL gives the last digits up to 99, instead of starting with 01 with a new AreaCode.
How do I put AreaCode in as a "resetter"?
Thanks again
Joejoe
April 8, 2007 at 11:28 pm
Try
SELECT A.AreaCode, A.AreaName,
A.AreaCode * 100 + (SELECT COUNT(*) FROM tablename Z WHERE Z.AreaCode = A.AreaCode AND Z.AreaName <= A.AreaName)
FROM tablename A
ORDER BY A.AreaCode, A.AreaName
K. Matsumura
April 9, 2007 at 3:02 am
Thanks Matsumura it works perfect! Just what I needed. Now I have a unique ID which can be order according to areas.
Joejoe
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply