问个sql查询问题

ipple 2006-10-17 10:42:29
只有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要删除

谢谢!
...全文
189 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ipple 2006-10-17
  • 打赏
  • 举报
回复
好冷啊,up一下
ipple 2006-10-17
  • 打赏
  • 举报
回复
呵呵,楼上二位把我想要的都删除了吧?
我想要留下的是name2中的一条,name4,name5...
chenjunjarysky 2006-10-17
  • 打赏
  • 举报
回复
up
allright_flash 2006-10-17
  • 打赏
  • 举报
回复
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)
子陌红尘 2006-10-17
  • 打赏
  • 举报
回复
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)
louifox 2006-10-17
  • 打赏
  • 举报
回复

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 tb1

select 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 行)


34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧