表中数据如下:name             idTom              1
Tom              2
Jerry            1
Jerry            2
Jerry            10
Jack             23
Jack             15。我要保留id最小的,Name唯一,如: Tom  1,  Jerry  1, Jack  15

解决方案 »

  1.   

    delete t
    from tb t
    where exists(select 1 from tb where name=t.name and id<t.id)
      

  2.   

    if object_id('[tb]') is not null drop table [tb] 
     go 
    create table [tb]([name] varchar(10),[id] int)
    insert [tb] select 'Tom',1
    union all select 'Tom',2
    union all select 'Jerry',1
    union all select 'Jerry',2
    union all select 'Jerry',10
    union all select 'Jack',23
    union all select 'Jack',15delete t
    from tb t
    where exists(select 1 from tb where name=t.name and id<t.id)select * from tb
    /*
    name       id
    ---------- -----------
    Tom        1
    Jerry      1
    Jack       15(3 行受影响)*/
      

  3.   

    delete 
      tb
    where
      exists(select 1 from tb t where t.name=tb.name and t.id>tb.id)
      

  4.   

    汗,反过来了delete 
      tb
    where
      exists(select 1 from tb t where t.name=tb.name and t.id<tb.id)select * from tb/**
    name       id          
    ---------- ----------- 
    Tom        1
    Jerry      1
    Jack       15(所影响的行数为 3 行)
    **/
      

  5.   

    delete from 表 t where not exists(select 1 from 表 where name = t.name and id < t.id)
      

  6.   

    delete a  where id not in (select min(id) from a group by name  ) 
      

  7.   

    我的习惯跟楼上基本一样,不过NOT IN效率不是很好,因为没有索引,我觉得换成 NOT EXISTS会比较好一点吧
      

  8.   

    子查询中按name取出最小的ID, 再与原表按name连接, 凡原表ID 大于 最小ID的全删除delete A
    from 表名 as A,
    (select name, min(id) as id
    from 表名
    group by name
    ) as v
    where A.name = v.name and
    A.id > v.id
      

  9.   

    if object_id('[tb]') is not null drop table [tb] 
     go 
    create table [tb]([name] varchar(10),[id] int)
    insert [tb] select 'Tom',1
    union all select 'Tom',2
    union all select 'Jerry',1
    union all select 'Jerry',2
    union all select 'Jerry',10
    union all select 'Jack',23
    union all select 'Jack',15delete t
    from tb t
    where exists(select 1 from tb where name=t.name and id<t.id)select * from tb这个正解
      

  10.   


    delete t where name in (select name from (select name,min(id) from t group by name ))
      

  11.   

    delete t
    from tb t
    where exists(select 1 from tb where name=t.name and id<t.id)
      

  12.   

    if object_id('[tb]') is not null drop table [tb] 
     go 
    create table [tb]([name] varchar(10),[id] int)
    insert [tb] select 'Tom',1
    union all select 'Tom',2
    union all select 'Jerry',1
    union all select 'Jerry',2
    union all select 'Jerry',10
    union all select 'Jack',23
    union all select 'Jack',15delete from [tb] where id not exists(select min(id) from [tb])delete 
      tb
    where
      exists(select 1 from tb t where t.name=tb.name and t.id<tb.id)