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

 

 

 

 

 

  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Carl_奕然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值