根据其他列值删除sql中的重复项

时间:2016-02-29 16:47:08

标签: sql sql-server tsql sql-delete

我想根据以下条件删除重复项。

我的表包含交叉关系等数据。第1列值存在于第2列中,反之亦然。

样本表

id     id1
-------------    
1      2     
2      1     
3      4     
4      3     
5      6     
6      5     
7      8     
8      7

我想从前两行删除1行,从第三行和第四行删除相同,第五和第六行相同,等等。

有人可以帮忙吗?

6 个答案:

答案 0 :(得分:1)

就像这样,你将只删除每组2行中的第二行:

CREATE TABLE [LIST_ID](
    [ID] [NUMERIC](4, 0) NOT NULL,
    [ID_1] [NUMERIC](4, 0) NOT NULL
);


INSERT INTO LIST_ID (ID, ID_1)
VALUES
(1, 2),
(2, 1),
(3, 4),
(4, 3),
(5, 6),
(6, 5);

WITH First_Row AS
(
SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) AS Row_Number, *
FROM LIST_ID
)
DELETE FROM First_Row WHERE Row_Number % 2 ='0';

SELECT * FROM LIST_ID;

答案 1 :(得分:1)

这个怎么样:

DELETE
  FROM  myTable
 WHERE  id  IN (
                SELECT  CASE WHEN id < id1 THEN id ELSE id1 END
                  FROM  myTable
               )

其中myTable是包含数据的示例表。

答案 2 :(得分:0)

根据您要保留的行,它会略有不同,但如果您的示例中确实存在简单的重复项,并且两个订单中都存在每个对,那么应该这样做:

DELETE FROM MyTable
WHERE ID > ID1

答案 3 :(得分:0)

declare @t table (id1 int, id2 int)

insert into @t (id1, id2)
values 
  (1, 2),
  (2, 1),
  (2, 1),
  (2, 1),
  (3, 4),
  (3, 4),
  (5, 6),
  (7, 8),
  (7, 6),
  (6, 7),
  (5, 0)

delete t2
from @t t1
inner join @t t2 on t2.id1 = t1.id2 and t2.id2 = t1.id1
where t2.id1 > t1.id1

select * from @t order by 1, 2

答案 4 :(得分:0)

declare @t table (id1 int, id2 int)

insert into @t (id1, id2)
values 
(1, 2),
(2, 1),
(3, 4),
(4, 3),
(5, 6),
(6, 5),
(7, 8),
(8, 7)
;

;with a as (
    select
      row_number() over (order by id1) rn
      ,t.id1
      ,t.id2
    from
      @t t
)
delete t from
  @t t
  join (
    select
       a.id1
      ,a.id2
    from
        a a
    where
      exists(
        select
          *
        from
          a b
        where
          a.id2 = b.id1 and a.id1 = b.id2 and a.rn > b.rn
      )
  ) c on t.id1 = c.id1 and t.id2 = c.id2
;

select * from @t;

/* OUTPUT
id1 id2
1   2
3   4
5   6
7   8
*/

答案 5 :(得分:0)

所以我能理解你要删除表中id = id1。

的行
delete from TableA as a
where exists(select 1 from TableA as b where a.id = b.id1)