简体   繁体   English

另一列上下文中的 SQL 唯一自动增量列

[英]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列的自动递增键的列,输出预期如下:

Prefix字首 Id ID
123 123 1 1
123 123 1 1
444 444 2 2
111 111 3 3
999 999 4 4
123 123 1 1
444 444 2 2

Do you know any simple solution how to do that?你知道如何做到这一点的任何简单的解决方案吗? I found out a solution for mysql but it is not working.我找到了 mysql 的解决方案,但它不起作用。 I am using sql management studio with sql server我正在使用带有 sql server 的 sql management studio

I tried solutions from this question but it does not work.我尝试了这个问题的解决方案,但它不起作用。 I have errors我有错误

You can use dense_rank() :您可以使用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:在 SQL Server 中,您可以将其表述为可更新的 CTE:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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