数据库MySQL--分组查询

事例使用文件:https://files.cnblogs.com/files/Vera-y/myemployees.zip

分组数据:group by 子句

分组查询语法:

  select 分组函数,列(要求是出现在group by的后面)

  from 表

  (where 筛选条件)  # where 必须连接from关键字

  group by 分组的列表

  (having 分组列表的条件)    #  分组后还有进行限制的条件

  (order by 子句)

1.简单的分组查询

例1.查询每个工种的最高工资

select max(salary), job_id   # job_id:需要分组的列

from employees

group by job_id;

例2.查询每个位置上的部门个数

select count(*),location_id

from departments

group by location_id;

2.添加筛选条件的分组查询

例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;

3.添加复杂的筛选条件

例1.查询那个部门的员工个数>2

SELECT COUNT(*), department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*)>2;

例2.查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资

SELECT MAX(salary), job_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING MAX(salary)>12000;

例3.查询领导编号>102的每个领导手下的最低工资>5000的领导编号是那个,以及其最低工资

SELECT MIN(salary), manager_id
FROM employees
WHERE manager_id>102   # 分组前的筛选
GROUP BY manager_id
HAVING MIN(salary)>5000;   # 分组后的筛选

注:分组筛选时,能用分组前筛选,就优先考虑使用,但当分组函数作为条件时,其肯定是放在having子句中

4.按表达式或函数分组

例1.按员工姓名的长度分组,查询每组的员工个数,筛选员工个数>5的有哪些

SELECT COUNT(*),LENGTH(last_name) as leng
FROM employees
GROUP BY LENGTH(last_name)
HAVING COUNT(*)>5;

(注:在MySQL中having和group by 后面是支持别名的,但是orcal等的数据库语言是不支持别名的)

5.按多个字段分组

例1.查询每个部门每个工种的员工 的平均工资

SELECT AVG(salary),department_id,job_id
FROM employees
GROUP BY department_id,job_id;      # 这里位置可以颠倒

6.添加排序

例1.查询每个部门每个工种的员工 的平均工资,按平均工资的高低显示

SELECT AVG(salary),department_id,job_id
FROM employees
GROUP BY department_id,job_id
ORDER BY AVG(salary) DESC;

(注:排序是在group by后面)

 

posted @ 2019-05-25 16:57  yin_zhaozhao  阅读(323)  评论(0编辑  收藏  举报