0

My Table is

+-----+----+----+------+
|EmpID|Name|Dept|Deptno|
+-----+----+----+------+
|1    |Abc |xyz |10    |
|1    |Abc |xyz |10    |
|2    |Def |pqr |20    |
+-----+----+----+------+

I want the output table as

+-----+----+----+------+
|EmpID|Name|Dept|Deptno|
+-----+----+----+------+
|1    |Abc |xyz |10    |
|2    |Def |pqr |20    |
+-----+----+----+------+

Conditions:

  1. Don't Use window functions.
  2. Table doesn't have any keys.
  3. Don't Use Temporary Tables.

I tried a Query:

delete from table_name where EmpId IN (
select EmpID from table_name group by EmpId,Name,Email,Deptno having count(*)>1 )

But, this query deletes all the rows which are having count > 1. But, I trying to delete the duplicate rows except one

3 Answers3

0

Use CTE + ROW_NUMBER to delete the duplicates alone

;WITH cte
     AS (SELECT Row_number()OVER(partition BY EmpId, Name, Email, Deptno ORDER BY (SELECT NULL)) AS rn,*
         FROM   table_name)
DELETE FROM cte
WHERE  rn > 1 

I think you can keep only EmpId in Partition BY

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
0
WITH CTE AS 
(
   SELECT EmpID,Name,Dept,Deptno,
       RN = ROW_NUMBER()OVER(PARTITION BY EmpID,Name,Dept,Deptno ORDER BY EmpID,Name,Dept,Deptno)
   FROM MyTable     
)
DELETE FROM CTE WHERE RN > 1
Zeina
  • 1,573
  • 2
  • 24
  • 34
-1

Apply Below 3 Query For Your Problem.

1.) ALTER TABLE dbo.test ADD AUTOID INT IDENTITY(1,1)

2.) SELECT * FROM dbo.test WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _ FROM dbo.test GROUP BY EmpId,Name,dept,Deptno)

3.) DELETE FROM dbo.test WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _ FROM dbo.test GROUP BY EmpId,Name,dept,Deptno)

krunal modi
  • 135
  • 10