Remove duplicate entries with different ids (Primary Key auto generate)

早过忘川 提交于 2019-12-24 19:43:28

问题


I have a table which has Ids as primary key with auto increment (random value) but has duplicates entries while checking the data from other columns, now need to delete those duplicate entries.

I have tried using distinct, MySQL 5 doesn't have rownum, so didn't try with rownum.

Currently, data is like this

Id     Col1
1anx    A
css2    B
3xcs    B
cd4v    C
xcv5    D
czv6    D

I want data to be like this:

Id     Col1
1anx    A
css2    B
cd4v    C
xcv5    D

回答1:


As an alternative to ROW_NUMBER, we can try using a join to a subquery which finds the smallest Id for each letter:

SELECT t1.Id, t1.Col1
FROM yourTable t1
INNER JOIN
(
    SELECT Col1, MIN(Id) As min_id
    FROM yourTable
    GROUP BY Col1
) t2
    ON t1.Col1 = t2.Col1 AND t1.Id = t2.min_id;



回答2:


This may help

IF OBJECT_ID('tempdb..#TempData') IS NOT NULL
    DROP TABLE #TempData
GO
CREATE TABLE  #TempData 
(
Id VARCHAR(10),
Col1 VARCHAR(10)
)
GO
INSERT INTO #TempData(Id,Col1) VALUES
( '1anx',   'A' ),
( 'css2',   'B' ),
( '3xcs',   'B' ),
( 'cd4v',   'C' ),
( 'xcv5',   'D' ),
( 'czv6',   'D' )
GO
;WITH DuplicateData
AS(
SELECT *,DENSE_RANK() OVER(PARTITION BY Col1 ORDER BY Id ASC) [Rank]
FROM #TempData
)
DELETE d
FROM DuplicateData d WHERE Rank > 1
GO
SELECT * FROM #TempData
GO



来源:https://stackoverflow.com/questions/56981400/remove-duplicate-entries-with-different-ids-primary-key-auto-generate

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