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);
本來還想寫嵌套聚合的情況的,但是覺得不要寫太多,
所以下一次寫一個嵌套聚合函數和開窗函數的細節