识别组中的重复项,其中一个值不同

时间:2017-07-28 22:24:42

标签: sql sql-server

USE TEMPDB
go

IF OBJECT_ID(N'#TEST', N'U') IS NOT NULL
    DROP TABLE dbo.#TEST


CREATE TABLE #TEST
(NAME VARCHAR(50),
line int,
RANKS INT)
INSERT INTO #TEST
(name, line,RANKS)
VALUES
('Tom',1, 1), --keep
('Tom',2, 1),--keep
('Toms',1, 0), --keep
('Toms',2, 0),--keep
('Dave',1, 0),--delete
('Dave',2, 0),--keep
('Dave',1, 1),--keep
('TIm',1,1),--keep
('TIm',1,0),--delete
('Matt',1,0),--delete
('Matt',1,1)--keep
  • 如果相同的名称和行在不同的等级下,那么我需要删除属于排名' 0'如果同一行的同一个人属于不同的等级,则应删除等级0以下的人。

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

delete t1
  from #TEST t1
 where exists(select *
                from #TEST t2
               where t2.NAME = t1.NAME
                 and t2.line = t1.line
                 and t2.RANKS <> t1.RANKS)
   and t1.RANKS = 0;