sum()求和
avg()求平均值
min()求最小值
max()求最大值
count()求数目
在分组函数中有几个重要的特征:
1.分组函数进行时自动忽略null
2.执行顺序为先分组后处理,如果没有分组则默认整张表为一组
常用SQL语句结构为:
select ...
from...
where...
group by...
order by....
其具体执行顺序为:
:from...
where...
group by...(分组)
select...
order by...
由此可见:如果将分组函数直接放置where后,分组这一步骤在where之后执行,与分组函数的特征相违背,所以不能将分组函数直接放置在where之后;
应用实例:
求每个部门的最高薪资,并且高于3000元
错误方法:
select depno,max(sal)
from emp
where
max(sal)>3000
--where 后面不能直接写上分组函数
group by
deptno;
正确方法:
引入having,having和group by是配套使用的,基本逻辑为分组后再对分组进行筛选
同时这也是引入having的必要性
select depno,max(sal)
from emp
group by
deptno;
having
max(sal)>3000;
但是having语句再效率方面不及where语句,所以从语句优化的方面出发,优先使用where,次而使用having
SQL语句优化
select
depno,max(sal)
from
emp
where
sal>3000
group by
deptno;
不能利用where来进行优化的例子:
求每个部门的最高平均薪资,并且平均工资高于3000元