分組函數(shù)
分組函數(shù)作用于一組數(shù)據(jù),并對一組數(shù)據(jù)返回一個(gè)值。
分組函數(shù).PNG
常用的組函數(shù)
avg
count
max
min
sum
例:
SQL> --工資總額
SQL> select sum(sal) from emp;
SUM(SAL)
----------
29025
SQL> --人數(shù)
SQL> select count(*) from emp;
COUNT(*)
----------
14
SQL> --平均工資
SQL> select sum(sal)/count(*) 一,avg(sal) 二 from emp;
一 二
---------- ----------
2073.21429 2073.21429
SQL> --平均獎(jiǎng)金
SQL> select sum(comm)/count(*) 一,sum(comm)/count(comm) 二,avg(comm) 三
2 from emp;
一 二 三
---------- ---------- ----------
157.142857 550 550
SQL> select count(*),count(comm) from emp;
COUNT(*) COUNT(COMM)
---------- -----------
14 4
null值:
SQL> --null值 5.組函數(shù)(多行函數(shù))自動(dòng)濾空
SQL> select count(*),count(nvl(comm,0)) from emp;
COUNT(*) COUNT(NVL(COMM,0))
---------- ------------------
14 14
SQL> --null值 5.組函數(shù)(多行函數(shù))自動(dòng)濾空;可以嵌套濾空函數(shù) 來屏蔽他的濾空功能
distinct關(guān)鍵字:
count(distinct expr) 返回expr非空不重復(fù)的記錄總數(shù)
語法:select count(distinct deptno) from emp;
分組數(shù)據(jù)
分組數(shù)據(jù).PNG
語法:group by 子句語法
可以使用group by子句將表中的數(shù)據(jù)分成若干組
注意:
在select列表中所有未包含在組函數(shù)中的列都應(yīng)該包含在group by子句中
包含在group by子句中的列不必包含在select列表中
例:
SQL> --求每個(gè)部門的平均工資
SQL> select deptno,avg(sal)
2 from emp
3 group by deptno;
SQL> --多個(gè)列的分組
SQL> select deptno,job,sum(sal)
2 from emp
3 group by deptno,job
4 order by 1;
使用多個(gè)列分組:
使用多個(gè)列分組.PNG
SQL> --多個(gè)列的分組
SQL> select deptno,job,sum(sal)
2 from emp
3 group by deptno,job
4 order by 1;
過濾分組:
過濾分組.PNG
SQL> --求平均工資大于2000的部門
SQL> select deptno,avg(sal)
2 from emp
3 group by deptno
4 having avg(sal) > 2000;
DEPTNO AVG(SAL)
---------- ----------
20 2175
10 2916.66667
注意:
不能再where子句中使用組函數(shù)
可以在having子句中使用組函數(shù)
SQL> --where和having的區(qū)別:where后面不能使用多行函數(shù)
SQL> --查詢10號部門的平均工資
SQL> select deptno,avg(sal)
2 from emp
3 group by deptno
4 having deptno=10;
select deptno,avg(sal)
2 from emp
3 where deptno=10
4 group by deptno
SQL 優(yōu)化原則:
3. 盡量使用where
having:先分組,再過濾
where:先過濾,再分組
所以where效率更高
group by的增強(qiáng)
SQL> /*
SQL> group by的增強(qiáng)
SQL> select deptno,job,sum(sal) from emp group by deptno,job
SQL> +
SQL> select deptno,sum(sal) from emp group by deptno
SQL> +
SQL> select sum(sal) from emp
SQL>
SQL> ===
SQL>
SQL> select deptno,job,sum(sal) from emp group by rollup(deptno,job);
SQL>
SQL> 抽象
SQL> group by rollup(a,b)
SQL> ==
SQL> group by a,b
SQL> +
SQL> group by a
SQL> +
SQL> group by null
SQL>
SQL> */
SQL> select deptno,job,sum(sal) from emp group by rollup(deptno,job);