更新重复的ID

问题描述 投票:0回答:1

我正在尝试找到一种更新一堆重复值的方法。

数据库架构如下所示:

ID | EntryId | Description | Category
1 | test1 | test description | fault
2 | test1 | test description | fault
3 | test1 | test description | fault
4 | test2 | test description | fault
5 | test2 | test description | fault
6 | test3 | test description | fault
7 | test4 | test description | fault
8 | test5 | test description | fault
9 | test5 | test description | fault
10 | test5 | test description | fault
11 | test6 | test description | fault
12 | test6 | test description | fault
... more entries below ...

我需要一个 sql 脚本以 test1a、test1b、test1c、test2a、test2b、test5a、test5b、test5c、test6a、test6b 的形式将字母表附加到重复的 EntryId 以及任何其他重复的 EntryId 并更新新值进入数据库。

已尝试使用下面的脚本,但由于我没有接受过 SQL 脚本方面的培训,所以来这里请求帮助。

SELECT ID, EntryId
, CONCAT( EntryId, CHAR((ROW_NUMBER() OVER(ORDER BY EntryId ASC)) + 96) ) AS NewEntryId
FROM table
WHERE EntryId
IN 
(   SELECT EntryId
    FROM table
    GROUP BY EntryId
    HAVING COUNT(*) > 1 
)

提前谢谢您!

sql sql-server
1个回答
1
投票

您可以使用 SQL 查询组合来识别重复的 EntryId 值,然后使用附加的字母表更新它们。下面是完成此任务的 SQL 脚本示例:

    -- Update duplicated EntryId values with appended alphabets
WITH CTE AS (
    SELECT 
        ID,
        EntryId,
        ROW_NUMBER() OVER(PARTITION BY EntryId ORDER BY ID) AS RowNum,
        CHAR(96 + ROW_NUMBER() OVER(PARTITION BY EntryId ORDER BY ID)) AS Alphabet
    FROM 
        YourTableName
)
UPDATE YourTableName
SET EntryId = CONCAT(EntryId, Alphabet)
FROM CTE
WHERE YourTableName.ID = CTE.ID
AND CTE.RowNum > 1;

将 YourTableName 替换为表的实际名称。此脚本识别重复的 EntryId 值,根据其出现情况为其分配字母表,然后使用新值更新 EntryId 列。

您还可以使用“cast”方法。请更喜欢这个 this 方法,因为我不能在这里写下所有内容

© www.soinside.com 2019 - 2024. All rights reserved.