ORACLE聚合函数细节


select * from emp order by mgr;
 

概要

select count(1), --14 sum(1), --14 count(*), --14 count(distinct mgr),--6 --很多人不知道可以这么用 count(all mgr), --13 --这里也是被遗忘的角落 count(mgr) --13 from emp;
 

 

计数

原意:查询有多少记录,就随便选了个字段

select count(mgr) from emp;

 

本来应该是14条记录,但是只查到了13条,原因是当选定字段进行聚合计算的时候该字段受到一些规则的限制,

具体发生了什么,下面具体举例说明

 

 

count函数调用方法是:

count([distinct|all] columnnameOrNumber)

 

select count(distinct mgr), --6
       count(all mgr), --13
       count(mgr) --13 
  from emp;

count(distinct mgr)的意思是计算mgr字段中所有非空的不同值的个数

count(all mgr)的意思是计算mgr字段中所有非空的值的个数

count(mgr)默认调用count(all mgr)

 

 

select count(1), --14
       sum(1),   --14
       count(*), --14
  from emp;

 

这里就很明朗了,不过不建议用count(*),涉及到sql解析的对资源消耗问题,

特别是实际的生产环境,比如我工作中遇到的表,一个表有500个字段,上亿条记录,

count(1)和count(*)还是会有很大差别的

 

当然还有很多其他聚合函数可以有([distinct|all] columnname)这种写法,

如avg,sum,stddev,variance,min,max...等等

 

最后送一个助消化的例子

select count( distinct mgr) from emp;

select count(1) from (select distinct mgr from emp);

 

 

本来还想写嵌套聚合的情况的,但是觉得不要写太多,

所以下一次写一个嵌套聚合函数和开窗函数的细节

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM