Insert numeric ID with interval

  • 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,

     AreaCodeAreaName
    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,

    AreaCodeAreaName  UniqueID
    102     LittleRock10201
    102     GreatArea10202
    102     Downtown10203
    102     WestSide10204
    102     EastSide10205
    102     SouthSide10206
    110     LittleRock11001
    110     GreatArea11002
    110     Downtown11003
    110     WilliamsTown11004
    110     EastSide11005
    110     SouthSide11006
    180     GeorgeTown18001
    180     LittleRock18002
    180     GreatArea18003
    192     Downtown19201
    192     Uptown19202
    192     WestSide19203
    192     EastSide19204
    192     SouthSide19205

    How do I create this kind of unique ID?  

    All help is appreciated

  • select

    areacode,

    areaname ,

    unique_id = areacode * 100 + rank() over(order by areacode, areaname)

    from table1

  • 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 

  • 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

  • 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 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply