Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSSQL Query to delete duplicate rows from a TABLE leaving distinct rows in table

I need to delete all duplicate rows except the first occurrence of similar rows from a Table Log having the same customer_id and deactivation_date. How do I achieve that with minimum number of sql statements.

I Am using MS SQL Server 2008 express edition.

like image 899
Akhil K Nambiar Avatar asked Apr 27 '12 07:04

Akhil K Nambiar


2 Answers

Something like:

DELETE FROM Log WHERE LogId NOT IN 
 (SELECT Min(LogId) FROM Log GROUP BY customer_id, deactivation_date)
like image 95
Fedor Hajdu Avatar answered Sep 21 '22 15:09

Fedor Hajdu


Or:

with cte as (
    select row_number() over (partition by customer_id, deactivation_date
    order by log_id) as rn
    from Log)
delete from cte
    where rn > 1;
like image 43
MicSim Avatar answered Sep 20 '22 15:09

MicSim