SQL删除重复记录并保留其余记录

时间:2011-11-02 11:27:19

标签: sql sql-server

我有2张桌子a和b。 A有5条记录,B有A和7行相同的记录。这是7行中相同的值。我想只删除B中的前5条记录,因为行号与A匹配。如何执行此操作。请帮帮我。

表:A

    col1    col2    col3    DuplicateCount
    1        2       n         1
    1        2       n         2
    1        2       n         3
    1        2       n         4
    2        2       m         1
    2        2       m         2

表b:

   col1 col2    col3    DuplicateCount
    1   2        n          1
    1   2        n          2
    1   2        n          3
    1   2        n          4
    1   2        n          5
    1   2        n          6

所需数据应位于表b中

col1 col2 col3 DuplicateCount

    1   2   n     5    
    1   2   n     6

这只是表b中的最后两行。

3 个答案:

答案 0 :(得分:1)

试试这个:

delete from TableB 
WHERE Id IN 
(
    select b.id 
    from TableB b, TableA a 
    WHERE b.Id = a.ID
)

答案 1 :(得分:0)

您可以使用TOP关键字删除前五个记录

DELETE TOP (select * from TableA a,TableB b where a.col1=b.col1 AND a.col2=b.col2 AND
a.col3=b.col3) FROM  TableA

注意:以下是根据ID

删除一个或多个记录的示例
DELETE From yourTable where ID in (2,3,4,5,6)

答案 2 :(得分:0)

我添加了id列来标识表B中的行,我不知道如何只删除一些没有id列的重复行:

declare @a table
(
    id int primary key,
    col1 int,
    col2 int,
    col3 varchar
)

declare @b table
(
    id int primary key,
    col1 int,
    col2 int,
    col3 varchar
)

insert into @a values (1,1,2,'n')
insert into @a values (2,1,2,'n')
insert into @a values (3,1,2,'n')
insert into @a values (4,1,2,'n')
insert into @a values (5,2,2,'n')
insert into @a values (6,2,2,'n')


insert into @b values (10,1,2,'n')
insert into @b values (20,1,2,'n')
insert into @b values (30,1,2,'n')
insert into @b values (40,1,2,'n')
insert into @b values (50,1,2,'n')
insert into @b values (60,1,2,'n')


delete from @b
where id in 
(
    (
        select t1.id from 
        (
            select 
                id, 
                cnt = count(*) over(partition by col1, col2, col3), 
                rn = row_number() over(partition by col1, col2, col3 order by id) 
            from @b
        ) t1
        join 
        (
            select 
                *, 
                cnt = count(*) over(partition by col1, col2, col3) 
            from @a
        ) t2 on 
            t1.cnt > 1 and t1.rn <= t2.cnt
    )
)

select * from @b