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用于给结果集分组,如果没有指定那么它把整个结果集作为一个分组

Sql去重查询数据介绍到这里,更多sql学习请参考编程字典sql教程 和问答部分,谢谢大家对编程字典的支持。


原文链接:https://blog.csdn.net/wuyoudeyuer/article/details/91384971?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163321812416780357217521%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=163321812416780357217521&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v29-6-91384971.pc_v2_rank_blog_default&utm_term=sql&spm=1018.2226.3001.4450