语法格式:
select 分组函数,列(要求出现在group by的后面)
from 表
【where】 筛选条件
group by 分组列表
【order by 子句】
注意:
查询列表必须特殊,要求是分组函数和group by 后出现的字段
总结特点:
1、分组查询中的筛选条件分为两类
数据库 位置 关键字
分组前筛前 原始表 group by子句前面 where
分组筛选后 分组后的结果集 group by子句后面 having
(1)分组函数做条件一定是放在having子句中
(2)能用分组前筛选的,就优先考虑使用分组前筛选
2、group by子句支持单个子句字段分组,多个字段分组(逗号),
表达式或函数
3、可以添加排序,放在最后
下面例题使用到的数据:
employees 员工表
salary job_id commission_pct departemt_id last_name manager_id
工资列 工资列 奖金率列 部门编号 员工名列 领导编号列
departments 部门表
department_id department_name manager_id location_id
部门标号列 部门名称列 领导编号列 位置编号列
#引入:查询每个部门的平均工资
SELECT AVG(salary) FROM employees;
#简单分组查询题
#1、查询每个工种的最高工资
SELECT MAX(salary),job_id
FROM employees
GROUP BY job_id;
#2、查询每个位置上的部门个数
SELECT COUNT(*),location_id
FROM departments
GROUP BY location_id;
#1、查询邮箱中包含a字符的,每个部门的平均工资
SELECT AVG(salary),department_id
FROM employees
WHERE email LIKE '%a%'
GROUP BY department_id;
#2、查询有奖金的每个领导手下员工的最高工资
SELECT MAX(salary),manager_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY manager_id;
#(1)查询每个员工的个数
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id;
#(2)根据(1)的结果进行筛选,查询哪个部门的员工数>2 having
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*)>2
ORDER BY COUNT(*);
#(1)查询每个工种有奖金的员工的最高工资
SELECT MAX(salary),job_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id;
#(2)根据(1)结果继续筛选,最高工资>12000
SELECT MAX(salary),job_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING MAX(salary)>12000;
#(1)查询每个领导
SELECT MIN(salary),manager_id
FROM employees
GROUP BY manager_id;
#(2)添加筛选条件:领导编号>120
SELECT MIN(salary),manager_id
FROM employees
WHERE manager_id>102
GROUP BY manager_id;
#(3)再添加筛选条件:最低工资>5000
SELECT MIN(salary),manager_id
FROM employees
WHERE manager_id>102
GROUP BY manager_id
HAVING MIN(salary)>5000
ORDER BY MIN(salary);
#(1)查询每个长度的员工个数
SELECT COUNT(*),LENGTH(last_name) len_name
FROM employees
GROUP BY LENGTH(last_name);
#(2)添加筛选条件
SELECT COUNT(*),LENGTH(last_name) len_name
FROM employees
GROUP BY LENGTH(last_name)
HAVING COUNT(*)>5;
#使用别名
SELECT COUNT(*) AS a,LENGTH(last_name) len_name
FROM employees
GROUP BY LENGTH(last_name)
HAVING a>5;
#查询每个部门每个工种的员工的平均工资
SELECT AVG(salary),department_id,job_id
FROM employees
GROUP BY job_id,department_id;
#综合
SELECT AVG(salary),department_id,job_id
FROM employees
WHERE department_id IS NOT NULL
GROUP BY job_id,department_id
HAVING AVG(salary)>10000
ORDER BY AVG(salary) DESC;