0

I got a list of around 5 users which have duplicate entries in the table. Here is the query i used to get the duplicate entries. Please suggest some easy way to delete few entries.

USE [DB]

SELECT UserName, COUNT(*) AS CountOF 
FROM UserDetails
WHERE RoleID = '2'
GROUP BY UserName
HAVING COUNT(*) > 1
2
  • 1
    Are you sure you are using MySQL (and not SQL Server)? What is the structure of the table? Commented May 26, 2017 at 2:49
  • I am using sql server. Sorry about the wrong tag Commented May 26, 2017 at 2:52

2 Answers 2

2

The use of square braces suggests SQL Server. If so, you can do:

WITH todelete as (
      SELECT ud.*,
             ROW_NUMBER() OVER (PARTITION BY RoleId, username ORDER BY RoleId) as seqnum
      FROM UserDetails
      WHERE RoleID = 2
     )
DELETE FROM todelete
    WHERE seqnum > 1;

Note: If RoleId is a number, then don't compare the value to a string.

Sign up to request clarification or add additional context in comments.

2 Comments

yes role id is a number. If there are 2 duplicate entries , the above query will delete one right ?
This logic will keep one value for each username for RoleId = 2.
0

need another uniq column like id or createtime more database support

with repeatData as (
    SELECT UserName,COUNT(*) as CountOF,min(id) as keepTag FROM UserDetails
    WHERE RoleID = '2'
    GROUP BY UserName
    HAVING COUNT(*)>1),
toDelData as (
    select id from UserDetails 
    where UserName in (SELECT UserName from repeatData) 
    and id not in (SELECT keepTag from repeatData) )
delete FROM UserDetails where id in (select id from toDelData )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.