简体   繁体   中英

SQL unique auto-increment column in the context of another column

I would like to create a column in the existing table with an auto-incrementing key based on Prefix column, with the output expected as follows:

Prefix Id
123 1
123 1
444 2
111 3
999 4
123 1
444 2

Do you know any simple solution how to do that? I found out a solution for mysql but it is not working. I am using sql management studio with sql server

I tried solutions from this question but it does not work. I have errors

You can use dense_rank() :

select t.*, dense_rank() over (order by prefix) as id
from t;

In SQL Server, you can phrase this as an updatable CTE:

with toupdate as (
      select t.*, dense_rank() over (order by prefix) as new_id
      from t
     )
update toupdate
    set id = new_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM