diff --git a/sql-queries-3/remove-duplicates/remove-duplicates-postgresql.sql b/sql-queries-3/remove-duplicates/remove-duplicates-postgresql.sql index 34d2418e..8b0f236c 100644 --- a/sql-queries-3/remove-duplicates/remove-duplicates-postgresql.sql +++ b/sql-queries-3/remove-duplicates/remove-duplicates-postgresql.sql @@ -23,4 +23,33 @@ USING ( ) t WHERE t.rn > 1 ) duplicate -WHERE Registration.id = duplicate.id; \ No newline at end of file +WHERE Registration.id = duplicate.id; + +-- Remove Duplicates Without a Unique Identifier + +-- Removing with CTE and USING clause +WITH RankedStudentRegistration AS ( + SELECT semester, year, course_id, student_id, + ROW_NUMBER() OVER ( + PARTITION BY semester, year, reg_datetime, course_id, student_id + ORDER BY (SELECT NULL) + ) AS rn + FROM Registration +) + +DELETE FROM Registration +USING RankedStudentRegistration +WHERE ( + Registration.semester = RankedStudentRegistration.semester + AND Registration.year = RankedStudentRegistration.year + AND Registration.course_id = RankedStudentRegistration.course_id + AND Registration.student_id = RankedStudentRegistration.student_id + AND RankedStudentRegistration.rn > 1 +); + +-- Removing using ctid system column +DELETE FROM Registration +WHERE ctid NOT IN ( + SELECT MIN(ctid) FROM Registration + GROUP BY semester, year, course_id, student_id, reg_datetime +); \ No newline at end of file diff --git a/sql-queries-3/remove-duplicates/remove-duplicates-sqlserver.sql b/sql-queries-3/remove-duplicates/remove-duplicates-sqlserver.sql index 7ec7fe1d..13bb182f 100644 --- a/sql-queries-3/remove-duplicates/remove-duplicates-sqlserver.sql +++ b/sql-queries-3/remove-duplicates/remove-duplicates-sqlserver.sql @@ -18,4 +18,26 @@ WITH COUNTED_DUPLICATES AS ( FROM Registration ) DELETE FROM COUNTED_DUPLICATES -WHERE rn > 1; \ No newline at end of file +WHERE rn > 1; + + +-- Remove Duplicates Without a Unique Identifier + +-- Removing with CTE and Inner Join +WITH RankedStudentRegistration AS ( + SELECT semester, year, course_id, student_id, + ROW_NUMBER() OVER ( + PARTITION BY semester, year, reg_datetime, course_id, student_id + ORDER BY (SELECT NULL) + ) AS rn + FROM Registration +) + +DELETE Registration FROM Registration +INNER JOIN RankedStudentRegistration +ON + Registration.semester = RankedStudentRegistration.semester + AND Registration.year = RankedStudentRegistration.year + AND Registration.course_id = RankedStudentRegistration.course_id + AND Registration.student_id = RankedStudentRegistration.student_id +WHERE RankedStudentRegistration.rn > 1; \ No newline at end of file