Assign identical ID to duplicates in SQL server

前端 未结 1 1422
渐次进展
渐次进展 2021-01-16 16:48

I would like to create an update query that would assign incremental IDs to values in my table. However, duplicate values should receive the same ID.

MyTable:

<
相关标签:
1条回答
  • 2021-01-16 17:28

    You can create a table with an auto increment id field an the word.

    MySQL:

    CREATE TABLE secondTable (
    id  int NOT NULL AUTO_INCREMENT,
    word  varchar(255) NULL,
    PRIMARY KEY (id)
    );
    

    MSSQL:

    CREATE TABLE [secondTable] (
    [id] int NOT NULL IDENTITY(1,1) ,
    [word] varchar NULL ,
    PRIMARY KEY ([id])
    )
    

    After that you insert the distinct values of word in your secondTable.

    INSERT INTO secondTable (word) SELECT distinct word FROM MyTable;
    

    At last you can update your table with the grouping IDs:

    UPDATE MyTable 
    SET ID = (SELECT id from secondTable where MyTable.word = secondTable.word)
    
    0 讨论(0)
提交回复
热议问题