Mysql基础(5)——分组查询

本文介绍了如何使用SQL进行复杂的数据查询,包括根据部门、工种和位置进行平均工资、最高工资和数量的分组统计,以及添加筛选条件如邮箱包含特定字符、有奖金的员工等。同时,展示了如何使用HAVING子句处理分组后的筛选,以及结合ORDER BY进行排序展示。这些技巧对于理解SQL中的聚合函数和分组操作至关重要。
摘要由CSDN通过智能技术生成

分组查询

在这里插入图片描述

在这里插入图片描述

引入:查询每个部门的平均工资

SELECT AVG(salary)
FROM employees
GROUP BY department_id;

案例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) departments_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:查询哪个部门的员工个数>2

SELECT COUNT(*), department_id
FROM employees
GROUP BY department_id;
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 manager_id,MIN(salary)
FROM employees
GROUP BY manager_id
WHERE manager_id>102 
HAVING MIN(salary)>5000;

当原表中有需要查询的数据条件时,如:领导编号,在原表有,则使用where manager_id>102 ;原表中没有而是通过查询后得出,则使用HAVING

按表达式或函数分组

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

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

按多个字段进行分组

案例:查询每个部门每个工种的员工的平均工资

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

添加排序

案例:查询每个部门每个工种的员工的平均工资,并且按平均工资的高低显示,按均工资降序且平均工资要>10000

SELECT AVG(salary),job_id,department_id
FROM employees
WHERE derpartment_id IS NOT NULL
GROUP BY department_id,job_id
HAVING AVG(salary)>100000
ORDER BY AVG(salary) DESC;

GROUP BY ;HAVING ;ORDER BY 都支持使用别名

例题

在这里插入图片描述

SELECT MAX(salary),MIN(salary),AVG(salary),SUM(salary),job_id
FROM employees
GROUP BY job_id
ORDER BY job_id;
SELECT MAX(salary)-MIN(salary) DIFFERENCE
FROM employees;
SELECT MIN(salary),manager_id
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary)>=6000;
SELECT department_id,count(*),AVG(salary)
FROM employees
GROUP BY department_id
ORDER BY AVG(salary) DESC;
SELECT COUNT(*),job_id
FROM employees
WHERE job_id IS NOT NULL
GROUP BY job_id
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值