简体   繁体   中英

SQL Server 2012: Check for Duplicates with Criteria

On SQL Server 2012 , I have a table which is similar as below:

Id  | SessionId  | TypeId  | Operation  | Data
------------------------------------------------------------------------
1   | ABC-123    | 6       | I          |<Record EmployeeName="Joe" />
2   | ABC-123    | 6       | U          |<Record EmployeeName="Joe" />

For us, the second row is a duplicate (I want to remove the record with the operation 'U' since I have an 'I' operation already) and I want to remove it. However, my SQL I tried actually removes other records also (see below).

;WITH CTE AS (
    SELECT [id],
           [SessionId],
           [TypeId],
           [Operation],
           [Data],
           RN = ROW_NUMBER() OVER (PARTITION BY [SessionId], [Data] ORDER BY [Data])
    FROM dbo.MyTable
    WHERE SessionId = @sessionId
)
DELETE FROM CTE
WHERE [Operation] = 'U'

Can you help?

DECLARE @t TABLE (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    SessionId VARCHAR(50),
    TypeId INT,
    Operation CHAR(1),
    Data XML
)

INSERT INTO @t (SessionId, TypeId, Operation, Data)
VALUES
    ('ABC-123', 6, 'I', '<Record EmployeeName="Joe" />'),
    ('ABC-123', 6, 'U', '<Record EmployeeName="Joe" />')

;WITH CTE AS (
    SELECT *,
           RN = ROW_NUMBER() OVER (PARTITION BY [SessionId], CHECKSUM(CAST([Data] AS NVARCHAR(MAX))) ORDER BY Id)
    FROM @t
)
DELETE FROM CTE
WHERE RN > 1
    AND Operation = 'U'

SELECT * FROM @t

output -

Id  SessionId    TypeId      Operation Data
--- ------------ ----------- --------- ------------------------------
1   ABC-123      6           I         <Record EmployeeName="Joe" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM