0

I have a table that has ID and EventDate. It has duplicate rows as I used Union of two tables. Now I got to have the rows with the minimum Eventdate and remove the other duplicates.

the table for eg

ID | Date
--- | ---
1 | 10/27/1993
1 | 10/27/1994
2 | 10/17/1993
2 | 08/15/1993

Delete duplicate rows based on condition

vba
  • 526
  • 8
  • 20

4 Answers4

2

You can use ROW_NUMBER:

;WITH CTE AS
(
   SELECT *,
          RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY EventDate)
   FROM dbo.YourTable
)
DELETE FROM CTE
WHERE RN > 1;
Lamak
  • 69,480
  • 12
  • 108
  • 116
0

Use this!

    delete A
    (
       SELECT *,
              RN = ROW_NUMBER() OVER(PARTITION BY [COLUMN] ORDER BY EventDate ASC),*
       FROM dbo.Your_Table
    ) AS A
where rn > 1
Fabiano Carvalho
  • 504
  • 1
  • 6
  • 17
0

As documentation (if we about MySQL) you cannot "delete from a table and select from the same table in a subquery".

So

CREATE table1 LIKE table2;
INSERT table2 SELECT * FROM table1; 
DELETE FROM table1
WHERE EXISTS(
  SELECT t2.id FROM table2 t2 WHERE table1.EventDate>t2.EventDate
);
DROP TABLE table2;

Where table1 you original table.

venoel
  • 463
  • 3
  • 13
0

If we talk about Firebird it is enough

DELETE FROM table1 t1_1
WHERE EXISTS(
  SELECT t1_2.id FROM table1 t1_2 WHERE t1_1.EventDate>t1_2.EventDate
);
venoel
  • 463
  • 3
  • 13