删除和删除表格中的重复记录

时间:2015-11-15 13:36:46

标签: sql sql-server sql-server-ce

我有这张桌子:

id  |  Name  | Age
==================
1   | AAA    | 22
1   | AAA    | 22
2   | BBB    | 33
2   | BBB    | 33
2   | BBB    | 33
3   | CCC    | 44
4   | DDD    | 55

我需要从此表中删除所有重复记录,并只留下一条记录。

表格如下:

id  |  Name  | Age
==================
1   | AAA    | 22
2   | BBB    | 33
3   | CCC    | 44
4   | DDD    | 55

我使用SQL Server CE for Mobile

由于

1 个答案:

答案 0 :(得分:1)

SQL Server中的一种简单方法是使用可更新的CTE:

with todelete as (
      select t.*,
             row_number(*) over (partition by id, name, age) as seqnum
      from t
    )
delete todelete where seqnum > 1;

唉,这在SQL Server CE中不起作用。因为您的行没有唯一标识符,我认为您需要创建一个临时表并使用如下方法:

create table temp_t (
    id int,
    name varchar(255),
    age int
   );

insert into temp_t select distinct * from t;

delete t;

insert into t select * from temp_t;

另一种方法使用额外的列而不是额外的表:

alter table t add tokeep int;

insert into t(id, name, age, tokeep)
    select distinct id, name, age, 1
    from t;

delete from t where tokeep is null;

alter table drop column tokeep;