I need to remove duplicates from a table:
;WITH cte as(
SELECT ROW_NUMBER() OVER (PARTITION BY [specimen id]
ORDER BY ( SELECT 0 ) ) RN
FROM quicklabdump)
delete from cte where RN>1
The column quicklabdumpID
is the primary key.
I would like to know how to keep only the largest quicklabdumpID
where there are multiple occurrences of [specimen id]
To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.
SELECT ALL columns FROM table; The syntax diagram is: SELECT [ALL | DISTINCT] columns FROM table; If a table has a properly defined primary key, SELECT DISTINCT * FROM table; and SELECT * FROM table; return identical results because all rows are unique.
Change your order by to quicklabdumpid DESC
.
WITH cte as(
SELECT ROW_NUMBER() OVER (PARTITION BY [specimen id]
ORDER BY quicklabdumpid DESC ) RN
FROM quicklabdump)
delete from cte where RN>1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With