只有20分了。
问题如下:
设一张表三个字段,id,name,company
现name有重复记录情况,举例如下:
1, name1, company1
2, name1, null
3, name2, null
4, name2, null
5, name3, company3
6, name3, null
7, name4, company4
8, name5, company5
...
如上,想要的结果如下:
1, 将重复的name中,company均为null的记录只留下一条,如name2要留下一条
2, 重复的name中,如果company有一个不为null就删除所有此name的记录,如name1,name3要删除谢谢!

解决方案 »

  1.   

    delete a 
    from 
        表 a 
    where 
        a.company is null 
        and 
        exists(select 1 from 表 where name=a.name and id<a.id and company is null)
      

  2.   

    delete from a 
    where  a.company is null  and 
        exists(select top from a where name=a.name and id<a.id and company is null)
      

  3.   

    呵呵,楼上二位把我想要的都删除了吧?
    我想要留下的是name2中的一条,name4,name5...
      

  4.   


    if object_id('tb')is not null
    drop table tb
    create table tb(id int,name varchar(20),company varchar(20))
    insert tb select
    1, 'name1', 'company1'
    union all select
    2, 'name1', null
    union all select
    3, 'name2', null
    union all select
    4, 'name2', null
    union all select
    5, 'name3', 'company3'
    union all select
    6, 'name3', null
    union all select
    7, 'name4', 'company4'
    union all select
    8, 'name5', 'company5'declare @a table(id int,name varchar(20),company varchar(20),r int,n int)insert into @a
    select *,r=(select count(*)from tb where tb.name=tb1.name),
    n=(select sum(case when company is null then 1 else 0 end) from tb where name=tb1.name) from tb tb1select id,name,company from @a
    where n=0
    union all
    select min(id),name,company from @a
    where r=n 
    group by name,company
    order by id(所影响的行数为 8 行)
    (所影响的行数为 8 行)id          name                 company              
    ----------- -------------------- -------------------- 
    3           name2                NULL
    7           name4                company4
    8           name5                company5(所影响的行数为 3 行)