Need to delete duplicate records from the table using row_number()

僤鯓⒐⒋嵵緔 提交于 2020-01-24 17:27:45

问题


I am having a table test having data as follows and I want to delete the trsid 124 and I have millions entry in my DB it is just a scenarion. Concept is to delete the duplicate entry from the table

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

I am trying something like

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

Even if I update the query which is Ok for me

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

But if i run both this query it deletes all the records from table test. And if i update it update both the records. I dont know what I am doing wrong here


回答1:


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

DELETE FROM cte
WHERE Row > 1



回答2:


Use the below query.

      ;WITH cte_1
         AS (SELECT ROW_NUMBER() OVER(PARTITION BY ID,NAME ORDER BY TrsId ) Rno,*
               FROM YourTable)
         DELETE
         FROM cte_1
         WHERE RNO>1



回答3:


WITH cte_DUP AS (
SELECT * FROM (
select <col1,col2,col3..coln>, row_number() 
over(partition by <col1,col2,col3..coln>
order by <col1,col2,col3..coln>  ) rownumber  
from <your table> ) AB  WHERE  rownumber > 1)

DELETE FROM cte_DUP WHERE ROWNUMBER > 1



回答4:


To find duplicate records we can write like below query,

;WITH dup_val 
     AS (SELECT a, 
                b, 
                Row_number() 
                  OVER( 
                    partition BY a, b 
                    ORDER BY b, NAME)AS [RANK] 
         FROM   table_name) 
SELECT * 
FROM   dup_val 
WHERE  [rank] <> 1; 


来源:https://stackoverflow.com/questions/39564777/need-to-delete-duplicate-records-from-the-table-using-row-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!