B表记录
  ID      Name      Aid
   1        a         1
   2        a         1
   3        ab        1
   4        b         2
   5        bc        2
   6        b         2
   7        bc        2
B表中的Name,Aid应该是唯一的
现在请给出清理B表重复记录的语句(删除语句),重复的记录中保留最小ID记录
清理后的结果应该是
 ID      Name      Aid
   1        a         1
   3        ab        1
   4        b         2
   5        bc        2应该怎么做啊

解决方案 »

  1.   


    drop table b
    create table b
    (
    id int,
    name varchar(10),
    aid int
    )
    insert into b
    select    1        ,'a',         1 union all
    select    2        ,'a',         1 union all
    select    3        ,'ab',        1 union all
    select    4        ,'b',         2 union all
    select    5        ,'bc',        2 union all
    select    6        ,'b',         2 union all
    select    7        ,'bc',        2
    delete from b
    from b
    inner join 
    (
     select *,row_number() over(partition by name,aid order by id ) rownum
     from b
    )t
    on t.id = b.id
       and t.rownum > 1
       select *
    from b
    /*
    id name aid
    1 a 1
    3 ab 1
    4 b 2
    5 bc 2
    */
      

  2.   

    create table Test_del
    (
    id int,
    name varchar(2),
    aid int
    )insert into test_del
    select  1        ,'a',         1 union all
    select  2        ,'a',         1 union all
    select 3        ,'ab',        1 union all
    select 4        ,'b',         2 union all
    select  5        ,'bc',        2 union all
    select 6        ,'b',         2 union all
    select 7        ,'bc',        2
       
    delete from Test_del 
    where name in (select name from Test_del group by name having COUNT(name) > 1)
    and id not in (select MIN(id) from Test_del group by name having COUNT(name) >1)