SQL Server 2012:检查带有条件的重复项

时间:2015-12-29 12:34:04

标签: sql-server tsql sql-server-2012

SQL Server 2012上,我有一个类似于下面的表格:

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

对于我们来说,第二行是重复的(我想删除带有'U'操作的记录,因为我已经有'I'操作了,我想删除它。但是,我试过的SQL实际上也删除了其他记录(见下文)。

;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'

你能帮忙吗?

1 个答案:

答案 0 :(得分:2)

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

输出 -

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