-- count
#作用:计算指定字段在查询结果中出现的个数
select count(employee_id) ,count(salary),count(salary*12)
from employees;
select count(1)
from employees;
select count(4)
from employees;
select count(*)
from employees;
-- 计算表中有多少记录,如何实现?
#方法一:count(常数)
#方法二:count(*)
#方法三:count(具体字段)
-- 注意:计算指定具体字段出现的个数时,是不计算NULL值的
select count(commission_pct) from employees;
select commission_pct from employees where
commission_pct is not null ;
#不为空是35 空的是72
#avg平均值
# 公式:AVG = sun/ count
select avg(salary),sum(salary)/count(salary),
avg(commission_pct),sum(commission_pct)/count(commission_pct),sum(commission_pct)/107
from employees;
# 直观的感觉
#需求:查询公司中平均奖金率
select avg(commission_pct) from employees;
#换一个场景:查询每一个中国人的平均工资是多少,其中有两亿人没有工作,大家说,这两亿人要不要计算在内?
select sum(commission_pct)/count(1) from employees;
#group by 的使用
#需求:查询各个部门的平均工资,最高工资
# 这是把107个员工看成了一个部门
select avg(salary),max(salary) from employees;#×
select avg(salary),max(salary) from employees
group by department_id; #√
# 需求:查询各个job_id的平均工资
#如:50号部门,各个工种的工资
select job_id,avg(salary) from employees
group by job_id;
#需求: 查询各个 department_id,job_id 的平均工资
select department_id,job_id, avg(salary) from employees
group by department_id,job_id;
select department_id,job_id,avg(salary) from employees
group by job_id, department_id;
#错误的,眼见不一定为实,但是没有报错
SELECT department_id,job_id,AVG(salary)
FROM employees
GROUP BY department_id;
#结论1:SELECT中出现的非组函数的字段必须声明在GROUP BY中
#反之,GROUP BY中声明的字段可以不出现在SELECT中
#结论2:GROUP BY声明在from后面,where的后面,ORDER BY前面,LIMIT前面