本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句
摘要:本文主要SQL语句中where的语法和使用
group by
语法:
select 分组函数,列(要求出现在group by的后面)
form 表
【where 筛选条件】
group by 分组的列表
【order by字句】
特点:
1、分组查询中的筛选条件分为两类
数据源 | 位置 | 关键字 | |
分组前筛选 | 原始表 | group by字句前面 | where |
分组后筛选 | 分组后的结果集 | group by字句后面 | having |
注意:如果用分组函数做条件进行筛选,一定是放在having子句中。
2、group by字句支持单个字段分组,也支持多个字段分组,还支持表达式和函数分组(用的较少)
3、也可以添加排序,放在最后
思考:查询每个部门的平均工资
select avg(salary) 平均工资, department_id 部门编号 from employees group by department_id;
#question1:查询每个工种的最高工资:
select max(salary), job_id from employees group by job_id;
#question2:查询每个位置上的部门个数
select count(*) 部门数量, location_id 位置编号 from departments group by location_id;
#或者是
select count(department_id ) 部门数量, location_id 位置编号 from departments group by location_id;
#question3:查询邮箱中包含a字符的,每个部门的平均工资 #分组前的筛选
select avg(salary), department_id, email from employees where email like '%a%' group by department_id;
#question4:查询每个领导手下有奖金的员工的最高工资。
select max(salary), manager_id from employees where commission_pct is not null group by manager_id;
#question5:查询员工个数>2的部门 having的用法 #分组后的筛选
select department_id from employees group by department_id having count(*) > 2;
#或者更直观的
select department_id from employees group by department_id having count(*) > 2;
#question6:查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资。
select job_id, max(salary) from employees where commission_pct is not null group by job_id having max(salary) > 12000;
#question7:查询领导编号>102的每个领导手下员工的最低工资>5000的领导编号是哪个,以及其最低工资
select manager_id, min(salary) from employees where manager_id > 102 group by manager_id having min(salary) > 5000;
#question8:按员工姓名的长度分组,查询每一组的员工的个数,筛选员工个数>5的有哪些
select count(*), length(last_name) from employees group by length(last_name) having count(*) > 5;
#别名的使用:要注意的是where后面不能放别名,group by和having可以,但是这种做法不常用,因为Oracle不支持where、group by、having后面放别名。
select count(*) c, length(last_name) len_name from employees group by len_name having c > 5;
#按照多个字段分组
#question9:查询每个部门每个工种的员工的平均工资
select avg(salary), department_id, job_id from employees group by department_id, job_id;
#添加排序
#question10:查询每个部门每个工种的员工的平均工资,并且按平均工资高低排序显示。
select avg(salary), department_id, job_id from employees group by department_id, job_id order by avg(salary),department_id;