I'm required to delete all duplicate entries of a table. The duplicates are identified by two non-key values num
(int) and com
(varbinary(512))..
My amateur-ish SQLfoo lead me to this non-functioning query (for testing reasons I just selected the duplicates)
SELECT num, com FROM TableA
WHERE num, com IN
(
SELECT count(*) AS co FROM TableA WHERE co > 1 GROUP BY num, com
)
How can I delete duplicates from TableA
identified by num
and com
?
(Working on Microsoft SQL Server Enterprise Edition v9.00.3042.00, i.e. SQL Server 2005 Service Pack 2)
edit
from the suggestions I've tried the following two queries. TableA features ~220 entries, where ~80 are duplicates.
first @dimitars suggestion
select ROW_NUMBER() OVER (PARTITION BY [num], com ORDER BY [num], com) as 'RowNumber', t1.*
into ##TableA
from TableA t1
delete t1
--select t1.*
from TableA t1
join ##TableC t2
on t2.[num]=t1.[num] and t2.com=t2.com
where t2.RowNumber > 1
resulting in every entry being deleted. And @marcelo miorellis suggestion
select * from TableA;
with cte as (
select *, row_number() over (partition by [num], com order by [num], com ) as Picker
from TableA
)
select cte
where Picker > 1
which gives me
Msg 207, Level 16, State 1, Line 7
Invalid column name 'Picker'.
Msg 207, Level 16, State 1, Line 6
Invalid column name 'cte'.
Best Answer