I have some duplicate values in my table.i want to delete one of those values
SQL> CREATE TABLE A (B NUMBER, C VARCHAR(1));
Table created.
SQL> INSERT INTO A VALUES (1, 'A');
1 row created.
SQL> INSERT INTO A VALUES (2, 'B');
1 row created.
SQL> INSERT INTO A VALUES (3, 'C');
1 row created.
SQL> INSERT INTO A VALUES (1, 'A');
1 row created.
SQL> INSERT INTO A VALUES (4, 'D');
1 row created.
SQL> INSERT INTO A VALUES (2, 'B');
1 row created.
SQL> INSERT INTO A VALUES (2, 'B');
1 row created.
SQL> SELECT * FROM A;
B C
---------- -
1 A
2 B
3 C
1 A
4 D
2 B
2 B
Note:
COMBINATION OF (1, A) REPEATS TWICE
COMBINATION OF (2, B) REPEATS THRICE
So, only 3 rows are to be deleted (one of combination 1, A; and two of
combination 2, B)
7 rows selected.
SQL> DELETE FROM A WHERE (B, C) IN (SELECT B, C -- All records repeating more than once
FROM (SELECT B, C, SUM(1) FROM A GROUP BY B, C
HAVING SUM(1) > 1)) AND ROWID NOT IN (SELECT MIN(ROWID) RID -- Rows not to be deleted
FROM A WHERE (B, C) IN (SELECT B, C
FROM (SELECT B, C, SUM(1) FROM A GROUP BY B, C HAVING SUM(1) > 1))
GROUP BY B, C);
3 rows deleted.
SQL> SELECT * FROM A;
B C
---------- -
1 A
2 B
3 C
4 D
No comments:
Post a Comment