当前位置:网站首页>sql查询去重统计的方法总结
sql查询去重统计的方法总结
2022-07-01 18:44:00 【无极小卒】
说到sql查询去重大家应该都首先会想到distinct 这个关键字。但有时候distinct并不适合某些特殊场景。
场景举例:
下图是我的文件存储表。现在有个需求就是统计上传文件的用户数是多少。
如果用distinct 去查询的话数量如下图。数量是8显然不对,正确的数量应该是4,重复的user_id不应该给我统计进去。
distinct 无法满足这种情况怎么办呢,还有一个常用的办法就是利用group by 进行分组统计。请直接看代码我是这么写的SELECT COUNT(1) AS countUser FROM (SELECT COUNT(1) FROM sys_file_info GROUP BY user_id ) AS a。这句话查询出来的就是正确的。
分组统计的思路,咱们先看下分组统计是什么样的。根据user_id分了4组,每个分组的数量是1,2,1,4。那么分组数就是去重后的用户数,即4组=4个用户。
咱们这时候统计一下分组的数量就可以了,怎么才能把分组的数量进行统计出来呢。很简单就是利用子查询,把分组查询出来的表当做一个伪表再进行统计一次就可以了。
SELECT COUNT(1) AS countUser FROM (SELECT COUNT(1) FROM sys_file_info GROUP BY user_id ) AS a 红色部分是形成一个伪表。蓝色部分是对伪表进行条数统计,那么就得到了分组的数量,即用户数。
边栏推荐
- Docker deploy mysql8.0
- Junit单元测试框架详解
- Helium transmission line of lake shore cryostat
- Lumiprobe 细胞成像研究丨PKH26细胞膜标记试剂盒
- 寶,運維100+服務器很頭疼怎麼辦?用行雲管家!
- 组队学习! 14天鸿蒙设备开发“学练考”实战营限时免费加入!
- ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
- Stanford, salesforce|maskvit: masked vision pre training for video prediction
- CDGA|从事通信行业,那你应该考个数据管理证书
- Solution of digital supply chain centralized purchase platform in mechanical equipment industry: optimize resource allocation and realize cost reduction and efficiency increase
猜你喜欢
M91 fast hall measuring instrument - better measurement in a shorter time
MySQL常用图形管理工具 | 黑马程序员
Example explanation: move graph explorer to jupyterlab
3. "Create your own NFT collections and publish a Web3 application to show them" cast NFT locally
PMP是被取消了吗??
Lake Shore—CRX-EM-HF 型低温探针台
Lumiprobe phosphide hexaethylene phosphide specification
B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
XML语法、约束
M91快速霍尔测量仪—在更短的时间内进行更好的测量
随机推荐
ECS summer money saving secret, this time @ old users come and take it away
[quick application] win7 system cannot run and debug projects using Huawei ide
中英说明书丨人可溶性晚期糖基化终末产物受体(sRAGE)Elisa试剂盒
The former 4A executives engaged in agent operation and won an IPO
Yyds dry inventory ravendb start client API (III)
ES6 summary "suggestions collection" of array methods find(), findindex()
Write it down once Net travel management background CPU Explosion Analysis
[live broadcast appointment] database obcp certification comprehensive upgrade open class
Viewing the whole ecology of Tiktok from a macro perspective
Solution of digital supply chain centralized purchase platform in mechanical equipment industry: optimize resource allocation and realize cost reduction and efficiency increase
MATLAB中subplot函数的使用
小红书上的爱情买卖
ETL development of data warehouse (IV)
Netease games, radical going to sea
Is PMP cancelled??
精益思想:来源,支柱,落地。看了这篇文章就懂了
11. Users, groups, and permissions (1)
Lumiprobe 活性染料丨吲哚菁绿说明书
Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit
Mipi interface, DVP interface and CSI interface of camera [easy to understand]