sql 查询去重

查询去重

distinct去重

select DISTINCT * from

解析:distinct去重很简单只用在查询字段前面加入distinct关键字就行,但此做法有一个问题,就是必须要所有的查询字段一模一样才能去重,如果其中有一个字段不重复就无法去重

 

group by 去重

select 查询字段 fromwhere  id in(select max(id) fromgroup by 去重分组字段)

解析:首先以要去重的字段分组 取得组内最大的id  然后根据id 查询的对应的信息就好,此方法需要有唯一字段,如:主键Id

 

没有唯一键group by 去重

select identity(int,1,1) as id,* into newtable(临时表) fromselect * from newtable where id in (select max(id) from newtable group by 去重分组字段) 

drop table newtable

解析:先将表into  写入到临时表newtable并加入自增Id,后续操作和group by  去重一致,然后删除(drop table)临时表

 

posted @ 2021-05-23 17:35  YorkQi  阅读(954)  评论(0编辑  收藏  举报