Sql去重查询数据

最近在工作过程中,面试过程中, 部分求职者或者同事,对sql怎么去重查询,不是太熟练

今天下午忙里偷闲, 整理了一下 

其实sql基本的查询 ,还是蛮有意思,   下面是我大致整理的几种去重查询 

1.存在2条一样的数据,  使用distinct

eg:   select distinct * from table(表名) where  条件

2.存在部分字段相同(有key, id  即唯一键) 如:id列不同,id类型为int,自增字段,使用聚合函数max或其他

eg:   select * from  table  where  id  in (

  select  max(id)  from  table  group by  [去重复字段表1,.....] having COUNT(*)>1

  )

 3.没有唯一键 ID,  需要借助创建临时表,来解决

 eg:  select  indentity (int,1,1) as  id , * into newtable(临时表)  from table

 select * from newtable where  id in  (select max(id)  from newtable group by [去重复字段表1,.....]) drop table newtable

4. id列不同,id类型为uniqueidentifier

① 使用row_number() over() he partition by  给每一组添加行号

select *,(row_number() Over(partition By'分组字段' order By '排序字段')) RowNum from

(select * from table where '分组字段'in (

select '分组字段' from table group by '分组字段' having count(*) >1)t1)

②将行号=1的数据插入临时表中

Select * into #A from (‘上面的sql语句’) t2 where t2.RowNum=1

注意:

1.row_number() over()是给行加行号的

2.partition  by用于给结果集分组,如果没有指定那么它把整个结果集作为一个分组 

 详细如: https://blog.csdn.net/wuyoudeyuer/article/details/91387434

猜你喜欢

转载自blog.csdn.net/wuyoudeyuer/article/details/91384971