0

I've got a table like this

DoctorName | IsOperDoc
  Albert   |     1
  Albert   |     1
  Albert   |     0
   Bill    |     0
   Bill    |     0
  Charlie  |     0
   Dave    |     1

I would like to delete duplicated rows and retain rows with IsOperDoc = 1 (also retains single row with IsOperDoc = 0 if the Doc is not OperDoc)

What I expect

DoctorName | IsOperDoc
  Albert   |     1
   Bill    |     0
  Charlie  |     0
   Dave    |     1
Chen
  • 171
  • 3
  • 14

2 Answers2

2

Try this:

WITH cte AS (
    SELECT  
        DoctorName , 
        IsOperDoc, 
        ROW_NUMBER() OVER (
            PARTITION BY 
                DoctorName , 
                IsOperDoc
            ORDER BY 
                DoctorName , 
                IsOperDoc
        ) row_num
     FROM 
        yourTable
)
DELETE FROM cte
WHERE row_num > 1;
Ankit Das
  • 640
  • 4
  • 16
1

Try this:

DECLARE @DataSource TABLE
(
    [DoctorName] NVARCHAR(128)
   ,[IsOperDoc] TINYINT
);

INSERT INTO @DataSource ([DoctorName], [IsOperDoc])
VALUES ('Albert', 1)
      ,('Albert', 1)
      ,('Albert', 0)
      ,('Bill', 0)
      ,('Bill', 0)
      ,('Charlie', 0)
      ,('Dave', 1);

WITH DataSource AS
(
    SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY [DoctorName] ORDER BY [IsOperDoc] DESC) AS [Rank]
    FROM @DataSource
)
DELETE FROM DataSource
WHERE [Rank] > 1;

SELECT *
FROM @DataSource;
gotqn
  • 42,737
  • 46
  • 157
  • 243