admin

需要使用row_number()从表中删除重复的记录

sql

我正在进行一个表测试,其中包含以下数据,并且我想删除trsid 124,并且我的数据库中有数百万个条目,这只是一个方案。概念是从表中删除重复的条目

--------------------------------------------
TrsId   |   ID  |   Name    |
--------------------------------------------    
123     |   1   |   ABC     |   
124     |   1   |   ABC     |

我正在尝试类似的东西

delete from test
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2

即使我更新对我来说没问题的查询

update test set id=NULL
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2

但是,如果我同时运行此查询,它将删除表测试中的所有记录。如果我更新它,则更新两个记录。我不知道我在做什么错


阅读 274

收藏
2021-06-07

共1个答案

admin

WITH cte AS
(
    SELECT ROW_NUMBER() OVER(PARTITION by ID ORDER BY name) AS Row
    FROM test
)

DELETE FROM cte
WHERE Row > 1
2021-06-07