0

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

2 Answers2

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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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

enter image description here

Khairul Alam
  • 1,266
  • 2
  • 11
  • 31