求怎样对一个字段去重~

buptseoly 2007-04-11 10:26:51
a 1
a 2
b 1
b 2
c 1
c 2
要求结果
a 1
b 1
c 1
第二个字段1或2均可,要从每组中只取一条记录。
...全文
322 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
buptseoly 2007-04-12
  • 打赏
  • 举报
回复
没有唯一字段ID
OracleRoob 2007-04-12
  • 打赏
  • 举报
回复
--如果表中有唯一字段ID,可以这么处理:

select *
from 表名 as t
where id = (select min(id) from 表名 where col1=t.col1)
buptseoly 2007-04-12
  • 打赏
  • 举报
回复
谢谢各位~实际问题如下:
col1是企业名称,后面的一些字段都是地址之类的信息
企业名称可能有重复
想对企业名称去重,每个企业只保留一条记录
一个sql如何实现
paoluo 2007-04-12
  • 打赏
  • 举报
回复
buptseoly() ( ) 信誉:100 Blog 加为好友 2007-4-12 0:14:33 得分: 0



没有唯一字段ID



-------
那就借用臨時表

Select RowID = Identity(Int, 1, 1), * Into #T From TableName
Select * From #T A Where RowID = (Select Min(RowID) From #T Where Col1 = A.Col1)
Drop Table #T
OracleRoob 2007-04-11
  • 打赏
  • 举报
回复

--因为有重复记录,所以用如下查,取到的不是1条,所以建议增加唯一ID字段

create table 表(col1 varchar(20),col2 int)
insert 表 select 'a', 1
insert 表 select 'a', 1
union all select 'a', 2
union all select 'b', 1
union all select 'b' , 2


select * from 表 ta
where not exists
(select 1 from 表 where col1=ta.col1 and col2<ta.col2)


drop table 表


/*

a 1
a 1
b 1


*/
zlp321002 2007-04-11
  • 打赏
  • 举报
回复
select * from 表 ta
where not exists
(select 1 from 表 where 字段1=ta.字段1 and 字段2<ta.字段2)
zlp321002 2007-04-11
  • 打赏
  • 举报
回复
select * from 表 ta
where not exists
(select 1 from 表 where 字段1=ta.字段1 and 字段2<ta.字段)
ankor 2007-04-11
  • 打赏
  • 举报
回复
create table t1(col1 varchar(20),col2 int)
insert t1 select 'a', 1
union all select 'a', 2
union all select 'b', 1
union all select 'b' , 2
ankor 2007-04-11
  • 打赏
  • 举报
回复
表:
create table t1(col1 varchar(20),col2 int)
insert t1 select 'a', 1
union all select 'a', 2
union all select 'b', 1
union all select 'b' , 2
ankor 2007-04-11
  • 打赏
  • 举报
回复

select * from t1 b where (select count(*) from t1 a
where col1=b.col1 and col2<=b.col2
)=1 order by col2
OracleRoob 2007-04-11
  • 打赏
  • 举报
回复
--如果表中有唯一字段ID,可以这么处理:


select *
from 表名 as t
where id = (select min(id) from 表名 where 字段1=t.字段1)
buptseoly 2007-04-11
  • 打赏
  • 举报
回复
实际上不止2个字段后面还有。。。该怎么写?
OracleRoob 2007-04-11
  • 打赏
  • 举报
回复
--对第一个字段分组,第二个字段取min()

如:


select 字段1, min(字段2) as 字段
from 表名
group by 字段1

34,576

社区成员

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

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