组函数特性
组函数处理多行返回一行。
组函数不计算空值。
where子句不可以使用组函数进行过滤,用having子句替代。
1.AVG
例1:求Toronto这个城市的员工的平均工资。
select 'Toronto',avg(salary)
from employees e,department d,locations l
where e.department_id = d.department_id
and d.location_id = l.location_id
and lower(l.city) = 'toronto'
例2:求有员工的各个城市的平均工资。
select city,avg(salary)
from employees e,department d,locations l
where e.department_id = d.department_id
and d.location_id = l.location_id
group by city
例3:查询平均工资高于8000的部门id和它的平均工资。
select department_id,avg(salary)
from employees
having avg(salary)>8000
group by department_id
例4:查询平均工资高于6000的job_title有哪些。
select j.job_title,avg(e.salary)
from jobs j
join employees e
on j.job_id = e.job_id
group by j.job_title
having avg(e.salary)>6000
2.COUNT
count(expr)返回的是expr不为空的记录总数。
例1:查询具有各个job_id的员工人数。
select job_id,count(employee_id)
from employees
group by job_id
3.MAX
数据类型为字符型,则输出Z开头的结果。
数据类型为日期,则输出最大(后)的日期。
例1:查询员工最高工资和最低工资的差距。
select max(salary),min(salary),max(salary) - min(salary) as "DEFERENCE"
from employees
4.MIN
例1:查询各个管理者手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内。
select manager_id,min(salary)
from employees
where manager_id is not null
group by manager_id
having min(salary) >= 6000
5.STDDEV 标准差
6.SUM
7.group by
如果只查询有组函数的列,则分组依据可以不写在select中
如果查询中既有组函数,也有其他列,则其他列全要写在group by 中
select中有的非组函数列,group by 一定要有;