1

I am using the SQL Server 2008R2, I have the following table named Emps

ID      Name      Title   
 1      XYZ       Manager
 2      ABC       CEO
 3      LMP       Clerk
 4      XYZ       Manager
 5      XYZ       Manager

Data in row 1,4 and 5 are same, Now what i want is to keep only one entry and delete all other existence of the duplicate record, one thing i should mention is my data is already inserted into database and i have to remove the duplicate data. Kindly Guide me is there any solution for it.

0

2 Answers 2

7

Try this one -

DECLARE @temp TABLE
(
      ID INT IDENTITY(1,1)
    , Name VARCHAR(10)
    , Title VARCHAR(10)
)

INSERT INTO @temp (Name, Title)
VALUES 
    ('XYZ', 'Manager'),
    ('ABC', 'CEO'),
    ('LMP', 'Clerk'),
    ('XYZ', 'Manager'),
    ('XYZ', 'Manager')

DELETE FROM t
FROM (
    SELECT 
          Name
        , Title
        , rn = ROW_NUMBER() OVER (PARTITION BY Name, Title ORDER BY 1/0) 
    FROM @temp
) t
WHERE rn > 1

SELECT * 
FROM @temp

Query cost -

enter image description here

Output -

ID          Name       Title
----------- ---------- ----------
2           ABC        CEO
3           LMP        Clerk
4           XYZ        Manager
Sign up to request clarification or add additional context in comments.

Comments

7
delete from emps
where id not in
(
  select min(id) from emps
  group by name, title
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.