delete from table where id not in(select max(id) from table group by col1,col2,col3.....colN)
)

解决方案 »

  1.   

    把要删除的放到临时表中,然后删除,然后再把一条数据从临时表中插入原表中。
    declare @field
    select @field = field1 from table1 group by filed1 having  count(field1)>1
    go
    select table1.* into #temp from table1 where field1=@field 
    go
    delete from table1 where field1=@field
    go
    insert table1 select top 1 * from #temp  where  field1=@field
    drop #temp
    go
      

  2.   

    select distinct * into ##yourT from yourtable
    where  id='id you need'delete yourtable
    where id='id you need'insert into yourtable
    select * from ##yourT思路就是先將重復的記錄distinct隻產生一條插入虛擬表中
    將重復記錄全刪除
    將你要的記錄從虛擬國表中插入即可
      

  3.   

    CrazyFor(Fan) 如果两条记录完全一样,这种方法不行。
    lyyrw(咋暖还寒) :这样写会有Bug
      field1 field2
        A     1
        B     2
        A     2
    你这样会把第三条记录删除,实际不能删。
    另外语句中间加go则后面的语句不能读变量。
    若不考虑效率,最简单的方法是:
    select distinct *
    into 临时表
    from 表delete 表insert into 表
    select * 
    from 临时表
      

  4.   

    Chiff(~o~) 
    说得很有道理
      

  5.   

    关键是表中有没有自增id
    如果有
    select distinct * from table 无效 
     CrazyFor(Fan) 的方法可行
    如果没有
    可用楼上的方法
      

  6.   

    --删除重复记录
    --删除临时表
    if object_id('tempdb..临时表名') is not null
    drop table tempdb..临时表名
    go
    --在表中增加一个自增字段
    ALTER TABLE 表名 ADD [自增字段名] [int] IDENTITY (1, 1) NOT NULL
    go
    SELECT min(自增字段名) As 自增字段名1,关键字段1,关键字段2 Into tempdb..临时表名 
    From 表名 Group By 关键字段1,关键字段2
    go
    DELETE 表名 Where 自增字段名 Not In (Select 自增字段名 From tempdb..临时表名)')
    GO
    --在表中删除自增字段
    ALTER TABLE 表名 DROP COLUMN [自增字段名]
    GO
      

  7.   

    其实CrazyFor(Fan) 和 WYZSC(007) 的方法都是一样的,只不过一个删除重复记录中id较大的那一条记录,而 WYZSC(007) 相反
    但CrazyFor(Fan) 必须指明程序中id是自增字段,如果不是则不能实现删除重复记录的效果