当前位置:网站首页>SQL中去去重的三种方式
SQL中去去重的三种方式
2022-07-26 16:52:00 【斯沃福德】
SQL去重是数据分析工作中比较常见的一个场景;
在 MySQL 中通常是使用 distinct 或 group by子句,但在支持窗口函数的 sql(如Hive SQL、Oracle等等) 中还可以使用 row_number 窗口函数进行去重。

需求: 统计 emp表中的员工数据中共有多少个部门 ?
1. distinct
select count(DISTINCT deptno ) from emp;
distinct 通常效率较低。它不适合用来展示去重后具体的值,一般与 count 配合用来计算条数。
注: distinct前面不能再有其他字段!
错误用法: SELECT ename , DISTINCT deptno FROM emp;
2. group by
select count(deptno) from
(select deptno from emp group by deptno)q;
3. row_number
使用ROW_NUMBER 记录每个partition内的排序,再用sum 记录排序中为1的,即为deptno的数量’
select sum( if(r =1,1,0) ) from
( select row_number() over(partition by deptno)as r from emp)q;
或者
select sum( case when r=1 then 1 else 0 end ) from
( select row_number() over(partition by deptno )as r from emp)q;
参考:https://blog.csdn.net/xienan_ds_zj/article/details/103869048
边栏推荐
- Is it safe to open an account online now? Who do you want to open a stock account?
- (25)Blender源码分析之顶层菜单Blender菜单
- Execution process of select statement in MySQL
- In the first half of the year, sales increased by 10% against the trend. You can always trust Volvo, which is persistent and safe
- CCS tm4c123 new project
- kudu设计-tablet
- Tensor operation in pytoch
- SQL注入(思维导图)
- 6-19漏洞利用-nsf获取目标密码文件
- 浅谈数据技术人员的成长之路
猜你喜欢

The latest interface of Taobao / tmall keyword search

Establishment of Eureka registration center Eureka server

Advantages of time series database and traditional database

Review the past and know the new MySQL isolation level

性能调优bug层出不穷?这3份文档轻松搞定JVM调优

About the adjustment of the game background, reading this article is enough

Ascend target detection and recognition - customize your own AI application

Just this time! Talk about the technical solutions of distributed system in detail

JS 闭包 模拟私有变量 面试题 立即执行函数IIFE

CCS tm4c123 new project
随机推荐
(25)Blender源码分析之顶层菜单Blender菜单
Analysis of the advantages of eolink and JMeter interface testing
现在网上开户安全么?股票开户要找谁?
Leetcode:1206. design jump table [jump table board]
Quickly build a development platform for enterprise applications
6-19漏洞利用-nsf获取目标密码文件
Data preprocessing of machine learning
[300 opencv routines] 240. Shi Tomas corner detection in opencv
Tensor operation in pytoch
Are CRM and ERP the same thing? What's the difference?
二层管理型交换机如何设置IP
After Australia, New Zealand announced the ban on Huawei 5g! Huawei official response
The latest interface of Taobao / tmall keyword search
Implementing DDD based on ABP -- aggregation and aggregation root practice
6-19 vulnerability exploitation -nsf to obtain the target password file
Shrimp Shope get commodity details according to ID API return value description
硬件开发与市场产业
Review the past and know the new MySQL isolation level
[cloud native kubernetes actual combat] kubeopertor installation tutorial
[machine learning] principle and code of mean shift